JavaScript

JavaScript SyntaxError – Unexpected Token

JavaScript is a widely used scripting language. Apart from its popularity, some challenges are raised while working with this scripting language. One of them is “SyntaxError – Unexpected token”. This error relates to the syntax error categories.

In this post, the possible reasons for SyntaxError Unexpected token are discussed. Furthermore, suitable guidelines are also provided to avoid this error in JavaScript.

How Does “SyntaxError – Unexpected Token” Occur in JavaScript?

There are a number of reasons behind this “syntax error – unexpected token”; some of them are listed below with examples.

Error 1: Extra Parenthesis

An error is given below in which a SyntaxError – Unexpected token has occurred.

function sum(x, y) {

  return x + y;

}}

In the above code, the function closing contains an extra parenthesis.

Output

The output shows that the “SyntaxError: Unexpected token” is thrown because of the extra parenthesis.

Error 2: Extra Colon

Another error is discussed here regarding a SyntaxError – Unexpected token and how to resolve the error.

const obj = {

  name:: "Java",

}

In the above code, the constant obj is initialized with name property. A Java value is assigned to this property.

Output

The “SyntaxError: Unexpected token” is thrown because of the extra colon.

How to Resolve “SyntaxError – Unexpected Token” in JavaScript?

In JavaScript, most programmers fix the errors by checking the mistakes in the code using the debugging method. In this method, you execute the chunks of code and finally resolve the errors. Furthermore, developers as well as users must be familiar with the latest version of the programming language to fix the problems. For instance, ES2015 refers to the latest version of JavaScript.

Solution of SyntaxError is provided here.

const obj = {

   name: "Java",

 }

 console.log(obj.name)

The script is ready for execution after removing the colon at the end of the property name.

The script is ready for execution after removing the colon in JavaScript.

The output shows the SyntaxError – Unexpected Token is resolved.

It is concluded that the “SyntaxError: Unexpected token” can be resolved using the proper notations.

Conclusion

In JavaScript, a SyntaxError occurs due to ignorance of programming guidelines. Like, if you add extra brackets or forget to close the function/method properly. These issues can be resolved by using the proper guidelines supported by ES2015(the latest version of JavaScript). This post demonstrates the reasons for occurrences of the JavaScript SyntaxError – Unexpected token with the help of suitable examples.

About the author

Syed Minhal Abbas

I hold a master's degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.