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.
- The Unexpected Token error belongs to Syntax Error object family.
- All the error objects in JavaScript are inherited from Error object.
- 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
Popular Posts
- Show / Hide div based on dropdown selected using jQuery
- Autosuggestion Select Box using HTML5 Datalist, PHP and MySQL with Example
- Custom Authentication Login And Registration Using Laravel 8
- Infinite Scrolling on PHP website using jQuery and Ajax with example
- Google Login or Sign In with Angular Application
- How to Convert MySQL Data to JSON using PHP
- How to change date format in PHP?
- Image Lazy loading Using Slick Slider
- Slick Slider Basic With Example
- php in_array check for multiple values
- Adaptive Height In Slick Slider
- Slick Slider Center Mode With Example
- How to Scroll to an Element with Vue 3 and ?
- JavaScript Multiple File Upload Progress Bar Using Ajax With PHP
- Slick Slider Multiple Items With Example