JavaScript Error Handling: Solving Unexpected Token
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.
SyntaxError: 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