Understanding Code Errors in JavaScript

It’s very easy to make a mistake while coding. All you have to do is type one character wrong in a variable name and things won’t work. So let’s take a look at some of the common errors that you’ll run into, and it doesn’t matter if you’re a new programmer or you’ve been doing it for a long time, it’s important to hunt down these errors quickly and fix them quickly.

Reference Errors in JavaScript

Example 1

   //Correct Code
   let productName = "Football";
   //Incorrect Code
   let productName = "Football";

In the above ‘correct‘ code, We are initializing productName variable and displaying its value in the console. It works fine without errors.

In the ‘incorrect‘ code, in the log function, we have passed the incorrect variable name (spelling mistake). If you run that code you will see ‘Uncaught ReferenceError: productame is not defined‘ error message.

Which clearly says that JavaScript engine not able to find ‘productame’ variable. Which is right. There is no name such as this.

Example 2

  //Incorrect code

Suppose you have forgotten to declare a variable name and you are trying to get value from it than it will throw same error. So always remember to declare a variable before using it.

undefined in JavaScript

   //Incorrect code
   let productName;

In the above example, we have defined the variable but we haven’t initialized it. So when we try to display its value in the console, it doesn’t pop up with any error but shows value as ‘undefined‘.

Syntax Errors in JavaScript

  //Incorrect code
  let class = "Football";

In the above example, we have defined variable with class name. You cannot do this because class is a reserved keyword. You cannot use reserved words as a variable name.

If you try to do this JavaScript engine will throw you an error as Uncaught ‘SyntaxError: Unexpected token ‘class’‘.

Here are some list of keywords in JavaScript keywords. You can see ‘class‘ is present in that.

In the upcoming articles, we will explore more topics of JavaScript.

Categories js

Subscribe Now!

Subscribe Us For Latest Articles