How to Fix SyntaxError: Unexpected end of input

Here are specific reasons why this error SyntaxError: Unexpected end of input occurs.

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

Reproduce the error

// 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

“Uncaught SyntaxError: Unexpected end of input” is generated when you try to parse a JSON that doesn’t have any data using the JSON.parse() function or $.parseJSON

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

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

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

Other solutions are the following:

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