JavaScript Error Handling: Solving Unexpected Token

Article By Digamber Rawat on
Today I am going to share with you, how to deal with unexpected tokens in JavaScript. Unexpected Token errors belong to SyntaxErrors. 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 tutorial, we will try to fix the Unexpected Token error. We will also find out where does this error fit into the JavaScript error family. Throughout this tutorial, you will get a chance to solve all the Unexpected Token errors which you often face in your day to day development phase.

Understand Errors in JavaScript

  • The Unexpected Token error belongs to SyntaxError object family.
  • All the error objects in JavaScript are inherited from Error object.
  • The SyntaxError object directly belongs to the Error object.

Using JavaScript Unexpected Token

Like 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 exprected syntaxes to be used whiel writing a programme.

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

Syntax​Error: Unexpected token examples

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

// Included extra comma
for (let i = 0; i < 5;, ++i) {
    console.log(i);
}

// Uncaught SyntaxError: Unexpected token ;

Solution

for (let i = 0; i < 5; ++i) {
    console.log(i);
}

/* output: 0 1 2 3 4 */

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

let a = 5;

if (a != 5) {
  console.log('true')
         else {
    console.log('false')
  }

// Uncaught SyntaxError: Unexpected token else

Solution

let a = 5;

if (a != 5) {
  console.log('true')
}
else {
  console.log('false')
}

// output: false
Digamber Rawat

Feel free to contact me, If you are looking for a freelance full stack Developer, with the following skills: Mongo DB, Express JS, Angualr 2+, Node JS, Loopback JS, Firebase, Ionic Framework and WordPress. I also offer remote contracting service to the clients across the globe. Hire Me