Syntax error unexpected expecting end of input

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

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

❌ 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');

  });

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 error

Code 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!

IMG_7793.jpeg

The Eagle’s Nest AirBnB Cabin on the Ohio River; One of my favorite places…

Last night I was on a coding tear, that moment when the solution is just crystal clear. That situation where something you’ve struggled with for days / weeks / months and then it all comest together.

The result of this was a whole bunch of code stuck in a single model and then this morning when I was ready to run it across the entire dataset, I got this crap:

ruby -c app/models/habit.rb
app/models/habit.rb:592: syntax error, unexpected end-of-input, expecting end

I censored hate this error. Line 592 is the end of the class and that means that the ruby parser just blithely skipped to the end and really has no useful positional information for you.

Note: If you’re not familiar with ruby -c, it is a syntax checker that makes sure your file is parseable. Think of it as a poor man’s lint.

My usual approach to finding this error is to cut our half the code in the file and then re-run the ruby -c process. And then repeat that until you get this:

ruby -c app/models/habit.rb
Syntax OK

And that’s how I ended up finding the error but the error was ridiculously subtle.

Here’s the error:

def self.with_feeds
  habits_with_feeds = []
  Habit.active.each do |habit|
    habits_with_feeds << if habit.has_feed?
  end
  habits_with_feeds
end

And here’s the corrected version of the method:

def self.with_feeds
  habits_with_feeds = []
  Habit.active.each do |habit|
    habits_with_feeds << habit if habit.has_feed?
  end
  habits_with_feeds
end

Now, this is subtle, so I’m going to just call it out. The issue was this line:

habits_with_feeds << habit if habit.has_feed?

versus

habits_with_feeds << if habit.has_feed?

Clearly, to the ruby parser, the lack of something being added to the array qualifies as a missing end. Yeah I get that but damn. I’m personally a huge fan of right hand if statements due to the reduction of 3 lines down to 1 but this is a case where they bit me hard. Sigh.

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Hoormazd Kia

In the Ruby foundation example video one of the examples involves building a speech class , but everytime I run the program i get the following error — «syntax error, unexpected end-of-input, expecting keyword_end»

here’s my speech-example.rb code.

class Speech
    def initialize
        print "What is the speech name? "
        @title = gets.chomp
        @lines = []
        while add_line
            puts "Line added."
        end
    end

    def title
        @title
    end

    def add_line
        puts "Add a line: (blank line to exit)"
        line = gets.chomp
        if line.length > 0
            @lines.push line
            return line
        else
            return nil
        end


    def each(&block)
        @lines.each { |line| yield line}
    end
end

speech = Speech.new
speec.each do |line|
    puts "[#{speech.title}] @{line}"
end

Oh, I’m also running the following version of Ruby — ruby 2.1.2p95

Thanks guys

2 Answers

Michael Hulet

You’re missing and end to close out your add_line method. This code works:

class Speech
    def initialize
        print "What is the speech name? "
        @title = gets.chomp
        @lines = []
        while add_line
            puts "Line added."
        end
    end

    def title
        @title
    end

    def add_line
        puts "Add a line: (blank line to exit)"
        line = gets.chomp
        if line.length > 0
            @lines.push line
            return line
        else
            return nil
        end
    #You were missing the end statement right here
    end


    def each(&block)
        @lines.each { |line| yield line}
    end
end

speech = Speech.new
speec.each do |line|
    puts "[#{speech.title}] @{line}"
end

Hoormazd Kia

PLUS

Thanks. guess I was just tired :)

I know that sometimes the errors we face in JavaScript can be difficult to debug. While with all the modern tools like Chrome developer tools etc the debugging has become far easier, there still are times when we come across issues that are tricky to debug. One such issue is the “Uncaught SyntaxError: Unexpected end of input” error in JavaScript.

Let us take a look at how can we debug such issues and what might be causing them.

What causes Unexpected end of Input in JavaScript?

Well, a large number of times, the cause of the “Uncaught SyntaxError: Unexpected end of input” error in JavaScript is missing parentheses, brackets, or quotes. Let’s take a look at the example below:

var addPost = function() {
   //add a new post when called
}

var editPost = function() {
   //edit the post when called
}

var deletePost = function() {
   //delete a post when called


var publishPost = function() {
   //publish a post when called
}

While everything looks good in the code above, this was throwing the Unexpected end of input error. However, if you look carefully, you’ll notice that the deletePost method has a missing closing bracket ( } ) which is actually causing the error.

On a javascript file with hundreds of lines of code, it can become very cumbersome to track the brackets line by line. There is an easier way to catch such errors and to avoid them too as shown in the next section.

How to fix Uncaught SyntaxError: Unexpected end of input error in JavaScript or jQuery?

Now that we know what causes this issue, the debugging method is also easy. While we can definitely look into the code and brackets and parentheses line by line, it would not be an effective method in the case of a large file. The easier way would be to make use of any tool.

One such tool I would recommend is https://jshint.com/ .

Once you visit JsHint, copy and paste your javascript code there. It would run an auto-scan of the code and list all the warnings and errors that the tool finds.

If you copy-paste the above code on JSHint, you’ll notice that it shows an ” Unmatched ‘{‘. ” warning. Once you hover over it, it would highlight the line with the deletePost method indicating that the missing bracket is in this method. Here is a screenshot that shows the issue on JsHint.

Screenshot showing the unmatched bracket warning in JsHint tool

Can the error be caused due to any other reason other than missing brackets etc?

Yes! While it is true that most of the time the issue is caused due to missing parentheses, brackets, or quotes, it has been noticed that whenever we try to parse an empty response from a JSON returned by Ajax call, the Unexpected end of input error can crop up too.

In such cases, add a conditional check to see if the data returned really has something within it before making use of the data returned.

For example, consider the following Ajax call in jQuery:

$.ajax({
   url: url,
   ...
   success: function (response) {

      if(response.data.length == 0){
         // this condition would prevent a blank json from being parsed
         // Empty response returned, maybe show an error etc
      }else{
        //Parse the JSON and use it
      }
   }
});

In the above code, you can notice that once we receive the response, we check if the length of the data returned is 0 i.e if the data returned is empty then maybe write a handler method or show an error to the user, otherwise, if there is data then parse it and use it.

To Summarize, the causes of Uncaught SyntaxError: Unexpected end of input error can be:

  • Missing Parentheses in the code
  • Missing Bracket in the code
  • Missing quote in the code, for string etc
  • Parsing an empty JSON

As I mentioned earlier, the “Uncaught SyntaxError: Unexpected end of input” error in JavaScript can be caused due to various reasons, however, the majority of the time it is because of missing parentheses, bracket, quote or because of parsing an empty JSON. However, an easy way to spot and avoid such issues is to run your javaScript through a validator like jsHint.com. If you are using webpack then you can even configure JSLinting or ESlint in your build process which would highlight such warnings and errors during the build time itself. Hope you would this article useful. Let us know in the comments!

Понравилась статья? Поделить с друзьями:
  • Syntax error unexpected expecting end of file перевод
  • Syntax error unexpected eof while parsing python
  • Syntax error unexpected eof php
  • Syntax error unexpected eof expecting
  • Syntax error unexpected endforeach