Jul 15, 2022 3:00:00 PM | Have a JavaScript Unexpected Token Error? Check Your Syntax
A deep look at the Unexpected Token Error in JavaScript, including a short examination of JavaScript’s syntax best practices.
Share
Today, we are discussing the Unexpected Token Error within our JavaScript Error Handling series. This JavaScript error is a subset of the SyntaxError. That means it only appears when attempting to execute code with an extra (or missing) character in the syntax.
Throughout this article, we’ll explore the Unexpected Token error, why it happens, and how to fix it.
The Technical Rundown
- All JavaScript error objects descend from the Error object or an inherited object therein.
- The SyntaxError object is inherited from the Error object.
- The Unexpected Token error is a specific type of SyntaxError object.
Why Does an Unexpected Token Occur?
JavaScript is particular about the way its syntax is written. While we don’t have time to cover everything that JavaScript expects (you can find that in the official documentation ), it’s essential to understand the basic premise of how JavaScript parsers work.
Statements written in JavaScript code are instructions that are concluded with a semicolon (;), and any spaces/tabs/newlines are considered whitespace. JavaScript parses code from left to right, converting statements and whitespace into unique elements.
- Tokens: These are words or symbols used by code to specify the application’s logic. These include +, -, ?, if, else, and var. These are reserved by the JavaScript engine and cannot be misused. They also cannot be used as part of variable names.
- Control characters: A subset of tokens that are used to direct the “flow” of the code into code blocks. These are used to maintain scope, with braces (< . >) and the like.
- Line terminators: As the name implies, a new line termination character.
- Comments: Comments are indicated using 2 forward-slash characters (//). The JavaScript engine will not parse comments.
- Whitespace: Any space or tab characters that do not appear within a string definition. Effectively, if it can be removed without changing the functionality of the code, it is whitespace.
When JavaScript parses code, it converts everything into these characters. Once that’s done, the engine attempts to execute our statements in order. In situations where the syntax is wrong, we might encounter an Unexpected Token error. This means the parser thinks there should be another element in a particular place instead of the token the parser found.
How to Fix an Unexpected Token
The best way to learn how to fix an Unexpected Token error is to go through a couple of examples.
Your Punctuation is Incorrect
Below, we have a simple call to the Math.max() method. This method accepts a list of numeric arguments and returns the largest number from that list.
Keen eyes will notice that we’ve accidentally included an additional comma (,) after our second argument (2,), which will be trouble for our parser:
try <
// Extra comma in Math.max
var value = Math.max(1, 2,);
console.log(value);
> catch (e) <
if (e instanceof SyntaxError) <
printError(e, true);
> else <
printError(e, false);
>
>
As expected, JavaScript wasn’t sure how to properly parse it. That’s why we received an Unexpected Token as a result:
// FIREFOX
SyntaxError: expected expression, got ‘)’
The problem could be one of two things:
- We wanted to list three arguments but forgot one: Math.max(1, 2, 3).
- We only wanted to list two arguments but included an additional comma: Math.max(1, 2).
JavaScript expected a third argument between that final comma and the closing parenthesis because of the extra comma in our method call. The lack of that third argument is what caused the error.
As mentioned earlier, there are many different types of Unexpected Token errors. Instead of covering all the possibilities, we’ll just look at one more common example.
You Have a Typo
The JavaScript’s parser expects tokens and symbols in a particular order, with relevant values or variables in between. Often, an Unexpected Token is due to an accidental typo. For the most part, you can avoid this by using a code editor that provides some form of auto-completion.
Code editors are beneficial when forming basic logical blocks or writing out method argument lists because the editor will often automatically provide the necessary syntax.
But, there’s a downside to relying too heavily on the auto-complete feature. If it auto-completes something and you change it, it’s up to you to go back and fix it.
For example, my code editor tried to fix the following snippet for me. So, I had to manually remove a brace (>) to get the desired result. Unfortunately, I forgot to go back and replace the missing brace. Because of this, an Unexpected Token error appeared in this simple if-else block:
try <
var name = «Bob»;
if (name === «Bob») <
console.log(`Whew, it’s just $
else <
console.log(«Imposter!»);
>
> catch (e) <
if (e instanceof SyntaxError) <
printError(e, true);
> else <
printError(e, false);
>
>
When JavaScript parses this, it expects that brace character, but instead, it gets the else:
// FIREFOX
SyntaxError: expected expression, got keyword ‘else’
Some keen observers may have noticed that even though we’re using the standard trappings of error capturing via a try-catch block to grab an instance of our SyntaxError, this code is never executed. The parser finds our SyntaxError and reports on it before it evaluates our catch block. You can catch Unexpected Token errors, but doing so typically requires the execution of the two sections (problematic code versus try-catch block) to take place in separate locations.
And, so, here comes our pitch.
Using Airbrake to Find JavaScript Errors
How long did it take you to find that one line of code causing the Unexpected Token error? With Airbrake Error & Performance Monitoring, you won’t have to sift through thousands of lines of code to find that one error that’s causing your application to fail. Instead, Airbrake will tell you EXACTLY where that error is, right down to the line of broken code. See for yourself with a free Airbrake dev account.
Note: We published this post in March 2017 and recently updated it in July 2022.
Решение — Uncaught SyntaxError: Unexpected token
Рассмотрим решение одной из часто встречаемых в консоли браузера ошибок Java Script — Uncaught SyntaxError: Unexpected token.
Для решения проблемы перейдите на строку с ошибкой (на изображении выше она под номером 23) и проверьте эту строку, а так же ближайшие к ней строки на наличие открывающего и закрывающего его элемента. Как правило вы обнаружите, что какой-то парный элемент отсутствовал.
Сообщение в консоли Unexpected / связано с регулярными выражениями. В таком случае номер строки в консоли указан верно.
Сообщение в консоли Unexpected ; обычно вызвано символом «;» внутри литерала объекта или массива, или списка аргументов вызова функции. В таком случае номер строки в консоли указан верно.
Для наглядности можно рассмотреть следующий код:

Консоль указывает на 23 строку, на ней мы видим фигурную скобку. Следующая закрывающая фигурная скобка находится на 27 строке. Но если посмотреть внимательнее, она относится к функции на 22 строке. Следовательно мы имеем открытую скобку на 23 строке, а закрывающая отсутствует. В итоге ошибка Uncaught SyntaxError: Unexpected token. Для решения ставим закрывающий элемент на 25 строке.
Итак, легко понять, что Unexpected token на самом деле получается благодаря невнимательности или случайному удалению парного элемента. Как правило быстрее найти ошибку помогает правильное форматирование когда.
Uncaught SyntaxError: Unexpected token
This is a common error in JavaScript, and it is hard to understand at first why it happens. But if you bear with me and remember that Bugs are a good thing you will be on your way in no time.
The JavaScript file you are linking to is returning 404 page. In other words, the browser is expecting JavaScript but it is returning HTML results.
Here is a simple example that may cause this error.
In the example above, when the user clicks on a link an ajax request is triggered to return json data. If the json data is returned correctly, everyone is happy and move on. But if it doesn’t, well we have to fix it. In situations like this, it’s often common to see the error:
Uncaught SyntaxError: Unexpected token <
Don’t run to stackoverflow right away. What the interpreter is telling us is that it found a character it was not expecting. Here the interpreter was expecting json, but it received < or HTML. If you check the response on your network developer tab, you will see that the response is HTML.
Another way you can get this error is if you add a script tag and have the src return HTML:
All it means is that the interpreter is expecting JavaScript or JSON and you are feeding it HTML/XML. If you don’t think you are returning HTML, check if you are not getting a 404.
How do I fix it?
Check the src path to your JavaScript to make sure it is correct. If you are making an Ajax request also check the path. Either the path is incorrect, or the file doesn’t exist.
Did you like this article? You can subscribe to read more awesome ones. RSS
SyntaxError: Unexpected token
Вместо определённой конструкции языка было использовано что-то другое. Возможно, просто опечатка.
Примеры
Ожидаемое выражение
Недопустимыми являются, к примеру, запятые после элементов цепочки выражений.
Правильным вариантом будет убрать запятую или добавить ещё одно выражение:
Недостаточно скобок
Иногда можно потерять скобки при использовании if :
На первый взгляд кажется, что скобки расставлены правильно, но обратите внимание, что || находится не в скобках. Необходимо заключить || в скобки: