Menu Close

How to solving unexpected token or error in javascript

javascript-error

Now I am going to share with you, how to deal with unexpected tokens in JavaScript. Unexpected Token or  errors belong to Syntax Errors. This error occurs when we try to call the code with the extra or missing character which does not belong to JavaScript family.

In this session, we will try to fix the Unexpected Token error. We will also find out where does this error fix into the JavaScript error family. Throughout this session, you will also get a chance to solve all the unexpected errors which you  face in your day to day development.

Understand errors in javascript

First of all, we have to understand what are all the errors occur in javascript.

  1. The Unexpected Token error belongs to Syntax Error object family.
  2. All the error objects in JavaScript are inherited from Error object.
  3. The Syntax Error object directly belongs to the Error object.

Javascript unexpected token

Compare to other programming languages JavaScript precisely talk about its errors. Errors are mostly occur when we don’t follow the proper programming rules. Here we need to understand the how does the JavaScript parsers work and what are the expected syntaxes to be used while writing a program.

Semicolon(;) in JavaScript plays a major role while writing a program. We should take care of whitespaces and semicolons like we do in other programming languages. Always consider writing JavaScript code from left to right.

Unexpected token examples

In the below example you can see when you put extra commas you get an error.

// Included extra comma
for (let i = 1; i < 5;, ++i) {
    console.log(i);
}
// Uncaught SyntaxError: Unexpected token , 

Solution:

for (let i = 1; i < 5; ++i) {
    console.log(i);
}
/* output:  1 2 3 4 */ 

You also get an error when you miss putting brackets in your if statements.

var a = 6;
if (a != 5) {
  console.log('true')
         else {
    console.log('false')
  }
  // Uncaught SyntaxError: Unexpected token 'else'  

Solution:

var a = 6;
if (a != 5) {
  console.log('true')
}
else {
  console.log('false')
}
// output: true 
Posted in JavaScript, Web Technologies

You can also read...