SyntaxError: Unexpected end of input – How to Fix

Uncaught SyntaxError: Unexpected end of input

“SyntaxError: Unexpected end of input” problem often occurs when we miss a closing parenthesis, bracket, or quote. Check out our instructions below to find the best solution that works for you.

What causes the error “SyntaxError: Unexpected end of input”?

Reproduce the “SyntaxError: Unexpected end of input” in JavaScript

Let’s take a look at one example:

function hello() {
  console.log('Welcome to LearnShareIt.com');

hello();

In this example, we can easily spot that a parenthesis is missing. Therefore, you will receive the Unexpected end of input error. To make it easier for you to understand, this simply means that the computer is telling you: “Hey man, you opened the parenthesis but forgot to close it.”

Here is another example: 

const obj = JSON.parse('');

When you are trying to parse an empty JSON string with JSON.parse(), it might also lead to getting the Unexpected end of input error

How to fix the “SyntaxError: Unexpected end of input” error

Solution 1: Add the missing parenthesis, bracket or quote!

The easiest way to fix this problem is to just add the closing parenthesis, bracket, or quote. 

function hello() {
  console.log('Welcome to LearnShareIt.com');
} 

hello();

Output:

Welcome to LearnShareIt.com

The parenthesis works like a door. If you open it, then you have to close it so that your program will work properly.

Solution 2: Use extensions/tools

We can use solution 1 without any problems for small projects or exercises. But for real-world larger projects, it is not always easy to do so. Let’s take a look at an example: 

const array = [1, 2, 3, 4, 5];

function even(){
  for (let i=0; i<5; i++) {
    if (array[i]%2===0){
      console.log(array[i]);
  }
}

even();

As you can see, the errors are less obvious in this example. Since then, we can use some online JavaScript Syntax Validators found easily on the Internet to help us check the syntax of our code.

Fixed code:

const array = [1, 2, 3, 4, 5];

function even(){
  for (let i=0; i<5; i++) {
    if (array[i]%2===0){
      console.log(array[i]);
    }
  }
}

even();

Output:

2
4

Solution 3: Avoid parsing empty JSON string

Make sure that your string is not empty before parsing.

Summary

The “SyntaxError: Unexpected end of input” error in JavaScript can be caused by various reasons, but the most common one is that we forget a closing parenthesis, bracket, or quote. To make it easier to handle large programs or projects, we can use a JavaScript validator to double-check the syntax.

Maybe you are interested in similar errors:

Leave a Reply

Your email address will not be published. Required fields are marked *