Uncaught syntaxerror unexpected end of input как исправить

Ситуация: вы пишете скрипт, в котором объявляете новые функции или используете уже встроенные. Вы уверены, что всё правильно, потому что делали так сотни раз в других проектах, но при запуске кода появляется такая ошибка:

❌ Uncaught SyntaxError: Unexpected end of input

Что это значит: браузер ждёт от вас или от кода продолжения ввода параметров или новых значений, но не находит их и падает с ошибкой.

Когда встречается: чаще всего это значит, что вы где-то потеряли закрывающие скобки. Вторая ситуация, более редкая — вы обрабатываете JSON-запрос и вам просто не приходят нужные данные (хотя должны бы). О том, что такое JSON-запросы и ответы, будет в отдельной статье — тема слишком большая и интересная для короткого ответа. Сейчас остановимся на первом варианте.

Что делать с ошибкой Uncaught SyntaxError: Unexpected end of input

Чтобы отловить и исправить эту ошибку, вам нужно посчитать и сравнить количество открытых и закрытых скобок в программе — как круглых (), так и фигурных {}. Скорее всего, вам не хватает и того, и другого (и точки с запятой после них).

Проще всего такую ошибку найти простым форматированием кода: когда все вложенные команды и параметры сдвигаются вправо табуляцией или пробелами. В этом случае легко найти разрыв в получившейся лесенке кода и добавить туда нужные скобки. Смотрите сами:

$(function () {
  $("#mewlyDiagnosed").hover(function () {
    $("#mewlyDiagnosed").animate({ 'height': '237px', 'top': "-75px" });
  }, function () {
    $("#mewlyDiagnosed").animate({ 'height': '162px', 'top': "0px" });
  });

Может показаться, что всё в порядке, но вот как выглядит этот код после форматирования:

$(function () {
  $("#mewlyDiagnosed").hover(function () {
    $("#mewlyDiagnosed").animate({ 'height': '237px', 'top': "-75px" });
  }, function () {
    $("#mewlyDiagnosed").animate({ 'height': '162px', 'top': "0px" });
  });

Сразу видно, что в конце скрипта не хватает строки с )}; — если их не поставить, браузер будет ждать продолжения ввода параметров вызова функции, не дождётся их и выдаст ошибку Uncaught SyntaxError: Unexpected end of input

Попробуйте сами. Найдите ошибку в этом коде:

$(function() {

  // Script to select all checkboxes

  $state.on('change', function(ev) {

    var $chcks = $("#example tbody input[type='checkbox']");

    if($state.is(':checked')) {

      $chcks.prop('checked', true).trigger('change');

    }else {

      $chcks.prop('checked', false).trigger('change');

  });

I have some JavaScript code that works in FireFox but not in Chrome or IE.

In the Chrome JS Console I get the follow error:

“Uncaught SyntaxError: Unexpected end of input”.

The JavaScript code I am using is:

<script>
 $(function() {
 $("#mewlyDiagnosed").hover(function() {
    $("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
 }, function() {
    $("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});
 });
</script>

It says the error is on the last line which is });

Phillip's user avatar

Phillip

5,31610 gold badges41 silver badges62 bronze badges

asked Oct 20, 2010 at 23:24

1

Add a second });.

When properly indented, your code reads

$(function() {
    $("#mewlyDiagnosed").hover(function() {
        $("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
    }, function() {
        $("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});
    });
MISSING!

You never closed the outer $(function() {.

answered Oct 20, 2010 at 23:27

SLaks's user avatar

SLaksSLaks

863k176 gold badges1900 silver badges1961 bronze badges

5

In my case, I was trying to parse an empty JSON:

JSON.parse(stringifiedJSON);

In other words, what happened was the following:

JSON.parse("");

answered May 29, 2014 at 17:31

falsarella's user avatar

falsarellafalsarella

12.2k9 gold badges69 silver badges115 bronze badges

1

http://jsbeautifier.org/ is helpful to indent your minified JS code.

Also, with Google Chrome you can use “pretty print”. See the example screenshot below showing jquery.min.js from Stack Overflow nicely indented right from my browser 🙂

enter image description here

falsarella's user avatar

falsarella

12.2k9 gold badges69 silver badges115 bronze badges

answered Jun 30, 2013 at 8:13

Hugo's user avatar

HugoHugo

2,05922 silver badges23 bronze badges

0

Formatting your code a bit, you have only closed the inner hover function. You have not closed the outer parts, marked below:

$(// missing closing)
 function() { // missing closing }
     $("#mewlyDiagnosed").hover(
        function() {
            $("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
        }, 
        function() {
            $("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});
        });

Sebastian Kaczmarek's user avatar

answered Oct 20, 2010 at 23:30

hvgotcodes's user avatar

hvgotcodeshvgotcodes

118k32 gold badges203 silver badges236 bronze badges

In my case, it was caused by a missing (0) in javascript:void(0) in an anchor.

Sebastian Kaczmarek's user avatar

answered Mar 4, 2018 at 20:53

Sam's user avatar

SamSam

9267 silver badges19 bronze badges

1

In my case, it ended up being a simple double quote issue in my bookmarklet, remember only use single quotes on bookmarklets. Just in case this helps someone.

answered Sep 20, 2012 at 19:14

Yëco's user avatar

YëcoYëco

1,54615 silver badges16 bronze badges

3

This error is mainly caused by empty returned ajax calls, when trying to parse an empty JSON.

To solve this test if the returned data is empty

$.ajax({
    url: url,
    type: "get",
    dataType: "json",
    success: function (response) {

        if(response.data.length == 0){
            // EMPTY
        }else{
            var obj =jQuery.parseJSON(response.data);
            console.log(obj);
        }
    }
});

Sebastian Kaczmarek's user avatar

answered Dec 30, 2015 at 17:41

Jimmy Obonyo Abor's user avatar

Jimmy Obonyo AborJimmy Obonyo Abor

7,25510 gold badges43 silver badges71 bronze badges

I got this error when I was trying to write a javascript bookmarklet. I couldn’t figure out what was causing it. But eventually I tried URL encoding the bookmarklet, via the following website: http://mrcoles.com/bookmarklet/ and then the error went away, so it must have been a problem with certain characters in the javascript code being interpreted as special URL control characters.

falsarella's user avatar

falsarella

12.2k9 gold badges69 silver badges115 bronze badges

answered Oct 27, 2014 at 17:20

user280109's user avatar

user280109user280109

1,4563 gold badges16 silver badges27 bronze badges

2

I got this since I had a comment in a file I was adding to my JS, really awkward reason to what was going on – though when clicking on the VM file that’s pre-rendered and catches the error, you’ll find out what exactly the error was, in my case it was simply uncommenting some code I was using.

answered Feb 20, 2017 at 5:48

Jack Hales's user avatar

Jack HalesJack Hales

1,56623 silver badges51 bronze badges

1

I also got this error pointing to the end of the last script block on a page, only to realize the error was actually from clicking on an element with a onclick="pagename" instead of onclick="window.location='pagename'". It’s not always a missing bracket!

answered Jul 9, 2019 at 14:09

justanotherguy's user avatar

justanotherguyjustanotherguy

5061 gold badge4 silver badges17 bronze badges

I think it could be almost any javascript error/typing error in your application.
I tried to delete one file content after another and finally found the typing error.

answered Oct 13, 2020 at 12:49

Petr's user avatar

PetrPetr

1,1931 gold badge15 silver badges27 bronze badges

1

“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.

  • Find more about JS Type of Errors

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

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:

  • ReferenceError: document is not defined
  • Unexpected token u in JSON at position 0
  • Uncaught SyntaxError: Unexpected token
  • Unexpected token o in json at position 1 error in js

Hello. My name is Khanh Hai Ngo. I graduated in Information Technology at VinUni. My advanced programming languages include C, C++, Python, Java, JavaScript, TypeScript, and R, which I would like to share with you. You will benefit from my content.


Name of the university: VinUni
Major: EE
Programming Languages: C, C++, Python, Java, JavaScript, TypeScript, R

Code formatting. Tabs or spaces, semi-colons or no semi-colons. It is a pretty controversial subject to many but it is quite important in some instances. If you are on a team, having a cohesive code format helps code readability among your peers. Even if you work alone, one big benefit of having a good sense of code formatting is to avoid syntactical errors.

JavaScript is pretty open when it comes to code format. There is a wide range of different ways to format your codebase in this language. What can happen if you don’t do it? Well, an example of a simple error that is often caused by code formatting issues is the Unexpected end of input error. How does it work?

The Problem

When JavaScript code is run it uses just in time compilation (JIT) to turn your code into something the computer can do. When this happens your code is read and certain things are expected about the code, for example having matching parentheses. If you received the Unexpected end of input error, odds are you are missing a closing curly brace } so the error is basically saying “you opened the curly brace but the code ended before it was closed”.

Here’s an example:

const writeHelloWorld = () => {
  console.log('hello world')

writeHelloWorld();Code language: JavaScript (javascript)

As you can see, the code is clearly missing a ending curly brace at the end of the arrow function which causes the error. So how does the code formatting mentioned earlier fit into this? Let’s look at a more real-world example:

const items = ['one', 'two', 'three'];

function parseItems() {
  for (let i = 0; i < items.length; i++) {
    if (items[i]) {
    console.log(items[i])
  }
}

parseItems();Code language: JavaScript (javascript)

In this example, it is a little less clear where the error is. The indentation is not very consistent so you might not notice that the if statement is actually missing a curly brace after which causes the error.

The Solution

Fortunately this is pretty simple to fix — you can just add your missing curly brace. In the above example:

const items = ["one", "two", "three"];

function parseItems() {
  for (let i = 0; i < items.length; i++) {
    if (items[i]) {
      console.log(items[i]); // indented this line over
    } // added this curly brace
  }
}

parseItems();Code language: JavaScript (javascript)

It can definitely be challenging to find a missing curly brace. Depending on your code editor of choice, you may be able to configure different colors for each pair of curly brace so it is easier to see which ones match and which ones don’t.

Another approach is to try and avoid these errors from the start. Using formatting tools such as Prettier or linting tools like ESLint can help a lot, at least in my experience.

Unexpected end of JSON input

There’s a chance that you received a similarly named but slightly different error: Unexpected end of JSON input. Rather than simply a missing curly brace, this error often occurs when you are trying to parse a JSON string that is itself missing a curly brace. Here’s an example:

const parseJson = (input) => JSON.parse(input);

const validJson = JSON.stringify({ hello: "world" });

const invalidJson = "{";

console.log(parseJson(validJson)); // prints out a valid object
console.log(parseJson(invalidJson)); // throws an errorCode language: JavaScript (javascript)

This can be simply fixed by ensuring the string you are parsing is valid JSON if you have control over that string. If you don’t, you can wrap the whole thing in a try / catch to be safe. Using the previous example:

const parseJson = (input) => {
  try {
    return JSON.parse(input);
  } catch (error) {
    return "error parsing input";
  }
};Code language: JavaScript (javascript)

If you add this to the parseJson function, you can now handle invalid JSON strings rather than getting an unexpected runtime error.

Conclusion

Hopefully this helps you see how useful good code formatting can be in your code, whether you work with a team or alone. Let us know if you have any other reasons why formatting can be so useful or how you do it in your own code setup. Thanks for reading!

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

There are specific reasons why this error SyntaxError: Unexpected end of input occurs. Some common reasons are: Missing 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.

Example

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 doesn’t have any data using JSON.parse() function or using $.parseJSON

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

  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 no need to write parsing logic on your code. Instead, remove that from the code.

That’s it for this tutorial.

Niva Shah

Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit “Cookie Settings” to provide a controlled consent.

Добавить комментарий