How to Solve SyntaxError: Unexpected end of input

To solve SyntaxError: Unexpected end of input in JavaScript, check your whole code and find out are you missing any brackets or parentheses. If this is the case, make sure to end each module that is required to be closed with proper parentheses.

When we were coding many times, we made some syntactical mistakes, which could further lead to SyntaxError as the name suggests SyntaxError that there is something wrong with the syntax defined.

There are specific reasons for this error SyntaxError: Unexpected end of input occurs. Some common reasons for getting this SyntaxError: Unexpected end of input error is: Missed closing parentheses, Quotes, or brackets, and When we try to parse an empty JSON with JSON.parse() or $.parseJSON.

  1. Missed closing parentheses, Quotes, or brackets.
  2. When we try to parse an empty JSON with JSON.parse() or $.parseJSON.

You will get the error when you forget to end your code with proper parentheses, quotes, or brackets.

The following code will generate SyntaxError: Unexpected end of input:

// Uncaught SyntaxError: Unexpected end of input
function sum(a, b) {
   return a + b;
   //forgot closing curly brace
   
   if (true) {
   // forgot closing curly brace
     const array = [1, 2 // forgot closing square bracket
     const object = { name: 'Diwakar' // forgot closing curly brace

For example, if you run the above file, you will get the following error.

Uncaught SyntaxError: Unexpected end of input

The Error “Uncaught SyntaxError: Unexpected end of input” also gets generated when you try to parse a JSON that dont have any date using JSON.parse() function or using $.parseJSON. For example, the following code will generate an error:

// Uncaught SyntaxError: Unexpected end of JSON input
console.log(JSON.parse(''));

console.log($.parseJSON(''));

As we discussed earlier, to solve the SyntaxError, check your whole code and find out are you missing any brackets or parentheses.

To debug your code, you can use an inbuilt debugger of JavaScript. If you don’t know how to use the debugger in JavaScript, you can read our article.

If you don’t want to come across this error because of the JSON parsing, you should take care of the below points.

  •  Wrap your parsing code inside the try/catch block.
  • Check whether your JSON is returning a valid response from the server or not.
  • If you want an empty response from the server, then no need to write parsing logic on your code. Instead, just remove that from the code.

That’s it for this tutorial.

See also

How to Solve Uncaught ReferenceError: required is not defined

How to solve reference error: window is not defined

How to solve reference error: document is not defined

Leave a Comment