I am learning Javascript via Codecademy and no have been stumped on this little piece here.
I have supposed to write an if else statement.
It shows me here in the following that there is a Syntac Error with a missing identifier:
var userAnswer = prompt("Are you feeling lucky, punk?");
if (userAnswer === "yes");
{
console.log("Batman hits you very hard. It's Batman and you're you! Of course Batman wins!");
}
else {
console.log("You did not say yes to feeling lucky. Good choice! You are a winner in the game of not getting beaten up by Batman.");
}
What is wrong with that…. There is no error in this example here:
if (age < 18)
{
console.log("We take no actions or responsibility. Play at your own risk!");
}
else
{
console.log("Enjoy the game");
}
tshepang
11.9k21 gold badges90 silver badges134 bronze badges
asked Feb 1, 2014 at 16:18
1
if (userAnswer === "yes");
Remove the semicolon.
answered Feb 1, 2014 at 16:20
2
There’s a semi-colon after the first conditional check. Also, you should always put the opening bracket of the conditional branch on the same line as the brackets
answered Feb 1, 2014 at 16:20
danwellmandanwellman
8,8898 gold badges60 silver badges87 bronze badges
var age;
age = prompt('How old are you?');
if (age < 18)
{
alert("We take no actions or responsibility. Play at your own risk!");
}
else if(age > 18)
{
alert("Enjoy the game");
}
answered May 18, 2015 at 19:46
1
remove the semicolon after
if (userAnswer === «yes»);
if you put the semicolon there, you are telling the script to stop there and not to render the next conditional statement that is «else»[SyntaxError: Unexpected token else]

vimuth
4,59123 gold badges72 silver badges112 bronze badges
answered Aug 1, 2022 at 8:49
@Hakerh400 @ematt321 I don’t know what [refack: redacted], but this is the pattern you want to use:
var multiTax = function (income) { if (income <= 500000) { income = income * 0.35; return income; } // ... if (income < 30000) { income = income * 0.10; return income; } else if (income >= 38701) { income = income * 0.22; return income; } else { income = income * 0.24; return income; } }; console.log(multiTax(500001));
this can be abbreviated to:
var multiTax = function (income) { if (income <= 500000) { return income = income * 0.35; } // ... if (income < 30000) { return income = income * 0.10; } else if (income >= 38701) { return income = income * 0.22; } else { return income = income * 0.24; } }; console.log(multiTax(500001));
which can be further abbreviated to:
var multiTax = function (income) { if (income <= 500000) { return income * 0.35; } // ... if (income < 30000 ) { return income * 0.10; } else if (income >= 38701) { return income * 0.22; } else { return income * 0.24; } }; console.log(multiTax(500001));
please pay attention.
Когда встречается. Допустим, вы пишете цикл for на JavaScript и вспоминаете, что там нужна переменная цикла, условие и шаг цикла:
for var i = 1; i < 10; i++ {
<span style="font-weight: 400;"> // какой-то код</span>
<span style="font-weight: 400;">}</span>
После запуска в браузере цикл падает с ошибкой:
❌ Uncaught SyntaxError: Unexpected token ‘var’
Что значит. Unexpected token означает, что интерпретатор вашего языка встретил в коде что-то неожиданное. В нашем случае это интерпретатор JavaScript, который не ожидал увидеть в этом месте слово var, поэтому остановил работу.
Причина — скорее всего, вы пропустили что-то из синтаксиса: скобку, кавычку, точку с запятой, запятую, что-то подобное. Может быть, у вас была опечатка в служебном слове и язык его не распознал.
Что делать с ошибкой Uncaught SyntaxError: Unexpected token
Когда интерпретатор не может обработать скрипт и выдаёт ошибку, он обязательно показывает номер строки, где эта ошибка произошла (в нашем случае — в первой же строке):

Если мы нажмём на надпись VM21412:1, то браузер нам сразу покажет строку с ошибкой и подчеркнёт непонятное для себя место:

По этому фрагменту сразу видно, что браузеру не нравится слово var. Что делать теперь:
- Проверьте, так ли пишется эта конструкция на вашем языке. В случае JavaScript тут не хватает скобок. Должно быть for (var i=1; i<10; i++) {}
- Посмотрите на предыдущие команды. Если там не закрыта скобка или кавычка, интерпретатор может ругаться на код немного позднее.
Попробуйте сами
Каждый из этих фрагментов кода даст ошибку Uncaught SyntaxError: Unexpected token. Попробуйте это исправить.
if (a==b) then {}
function nearby(number, today, oneday, threeday) {
if (user_today == today + 1 || user_today == today - 1)
(user_oneday == oneday + 1 || user_oneday == oneday - 1)
&& (user_threeday == threeday + 1 || user_threeday == threeday - 1)
return true
else
return false
}
var a = prompt('Зимой и летом одним цветом');
if (a == 'ель'); {
alert("верно");
} else {
alert("неверно");
}
alert(end);
Сообщение
SyntaxError: expected expression, got "x" SyntaxError: expected property name, got "x" SyntaxError: expected target, got "x" SyntaxError: expected rest argument name, got "x" SyntaxError: expected closing parenthesis, got "x" SyntaxError: expected '=>' after argument list, got "x"
Тип ошибки
Что пошло не так?
Вместо определённой конструкции языка было использовано что-то другое. Возможно, просто опечатка.
Примеры
Ожидаемое выражение
Недопустимыми являются, к примеру, запятые после элементов цепочки выражений.
for (let i = 0; i < 5,; ++i) {
console.log(i);
}
// SyntaxError: expected expression, got ';'
Правильным вариантом будет убрать запятую или добавить ещё одно выражение:
for (let i = 0; i < 5; ++i) {
console.log(i);
}
Недостаточно скобок
Иногда можно потерять скобки при использовании if:
function round(n, upperBound, lowerBound){
if(n > upperBound) || (n < lowerBound){
throw 'Число ' + String(n) + ' больше, чем ' + String(upperBound) + ', или меньше, чем ' + String(lowerBound);
}else if(n < ((upperBound + lowerBound)/2)){
return lowerBound;
}else{
return upperBound;
}
} // SyntaxError: expected expression, got '||'
На первый взгляд кажется, что скобки расставлены правильно, но обратите внимание, что || находится не в скобках. Необходимо заключить || в скобки:
function round(n, upperBound, lowerBound){
if((n > upperBound) || (n < lowerBound)){
throw 'Число ' + String(n) + ' больше, чем ' + String(upperBound) + ', или меньше, чем ' + String(lowerBound);
}else if(n < ((upperBound + lowerBound)/2)){
return lowerBound;
}else{
return upperBound;
}
}
Home » Javascript » JavaScript Error Handling: Solving Unexpected Token
Today I am going to share with you, how to deal with unexpected tokens in JavaScript. Unexpected Token errors belong to SyntaxErrors. This error occurs when we try to call the code with the extra or missing character which does not belong to JavaScript family.
In this tutorial, we will try to fix the Unexpected Token error. We will also find out where does this error fit into the JavaScript error family. Throughout this tutorial, you will get a chance to solve all the Unexpected Token errors which you often face in your day to day development phase.
Understand Errors in JavaScript
- The Unexpected Token error belongs to SyntaxError object family.
- All the error objects in JavaScript are inherited from Error object.
- The SyntaxError object directly belongs to the Error object.
Like other programming languages JavaScript precisely talk about its errors. Errors are mostly occur when we don’t follow the proper programming rules. Here we need to understand the how does the JavaScript parsers work and what are the exprected syntaxes to be used whiel writing a programme.
Semicolon(;) in JavaScript plays a vital role while writing a programme. We should take care of whitespaces and semicolons like we do in other programming languages. Always consider writing JavaScript code from left to right.
SyntaxError: Unexpected token examples
In the below example you can see when you put wrong trailing commas you get an error.
// Included extra comma
for (let i = 0; i < 5;, ++i) {
console.log(i);
}
// Uncaught SyntaxError: Unexpected token ;
Solution
for (let i = 0; i < 5; ++i) {
console.log(i);
}
/* output: 0 1 2 3 4 */
You also get an error when you miss putting brackets in your if statements.
let a = 5;
if (a != 5) {
console.log('true')
else {
console.log('false')
}
// Uncaught SyntaxError: Unexpected token else
Solution
let a = 5;
if (a != 5) {
console.log('true')
}
else {
console.log('false')
}
// output: false
Recommended Posts:
Improve Article
Save Article
Improve Article
Save Article
Like other programming languages, JavaScript has define some proper programming rules. Not follow them throws an error.An unexpected token occurs if JavaScript code has a missing or extra character { like, ) + – var if-else var etc}. Unexpected token is similar to syntax error but more specific.Semicolon(;) in JavaScript plays a vital role while writing a programme.
Usage: To understand this we should know JavaScript also has a particular syntax like in JavaScript are concluded by a semi-colon(;) and there are many rules like all spaces/tabs/newlines are considered whitespace. JavaScript code are parsed from left to right, it is a process in which the parser converts the statements and whitespace into unique elements.
- Tokens: All the operator (+, -, if, else…) are reserved by the JavaScript engine.So, it cannot be used incorrectly .It cannot be used as part of variable names.
- Line terminators: A JavaScript code should end with semi-colon(;).
- Control characters: To control code, it is important to maintain braces({ }) in a code. It is also important to defines the scope of the code.
- Comments: A line of code written after // is a comment. JavaScript ignores this line.
- Whitespace: It is a tab/space in code.Changing it does not change the functionality of the code.
Therefore JavaScript code is very sensitive to any typo error. These examples given below explain the ways that unexpected token can occur.
Example 1: It was either expecting a parameter in myFunc(mycar, ) or not, .So it was enable to execute this code.
javascript
<script>
function multiple(number1, number2) {
function myFunc(theObject) {
theObject.make = 'Toyota';
}
var mycar = {
make: 'BMW',
model: 'Q8-7',
year: 2005
};
var x, y;
x = mycar.make;
myFunc(mycar, );
y = mycar.make;
</script>
Output:
Unexpected end of input
Example 2: An unexpected token ‘, ‘occurs after i=0 which javascript cannot recognize.We can remove error here by removing extra.
javascript
<script>
for(i=0, ;i<10;i++)
{
document.writeln(i);
}
</script>
Output:
expected expression, got ', '
Example 3: An unexpected token ‘)’ occur after i++ which JavaScript cannot recognize.We can remove error here by removing extra ).
javascript
<script>
for(i=0;i<10;i++))
{
console.log(i);
}
</script>
Output
expected expression, got ')'
Example 4: At end of if’s body JavaScript was expecting braces “}” but instead it got an unexpected token else.If we put } at the end of the body of if.
javascript
<script>
var n = 10;
if (n == 10) {
console.log("TRUE");
else {
console.log("FALSE");
}
</script>
Output
expected expression, got keyword 'else'
Similarly, unnecessary use of any token will throw this type of error. We can remove this error by binding by following the programming rules of JavaScript.
The JavaScript exceptions «unexpected token» occur when a specific language construct was expected, but something else was provided. This might be a simple typo.
Message
SyntaxError: expected expression, got "x" SyntaxError: expected property name, got "x" SyntaxError: expected target, got "x" SyntaxError: expected rest argument name, got "x" SyntaxError: expected closing parenthesis, got "x" SyntaxError: expected '=>' after argument list, got "x"
Error type
What went wrong?
A specific language construct was expected, but something else was provided. This might be a simple typo.
Examples
Expression expected
For example, when chaining expressions, trailing commas are not allowed.
for (let i = 0; i < 5,; ++i) { console.log(i); }
Correct would be omitting the comma or adding another expression:
for (let i = 0; i < 5; ++i) { console.log(i); }
Not enough brackets
Sometimes, you leave out brackets around if statements:
function round(n, upperBound, lowerBound) { if (n > upperBound) || (n < lowerBound) { throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`); } else if (n < (upperBound + lowerBound) / 2) { return lowerBound; } else { return upperBound; } }
The brackets may look correct at first, but note how the || is outside the brackets. Correct would be putting brackets around the ||:
function round(n, upperBound, lowerBound) { if ((n > upperBound) || (n < lowerBound)) { throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`); } else if (n < (upperBound + lowerBound) / 2) { return lowerBound; } else { return upperBound; } }
See also
SyntaxError
JavaScript
- ReferenceError: assignment to undeclared variable «x»
- The JavaScript strict mode-only exception «Assignment to undeclared variable» occurs when value has been assigned an ReferenceError in strict mode only.
- ReferenceError: reference to undefined property «x»
- The JavaScript warning «reference to undefined property» occurs when attempted access an object which doesn’t exist.
- TypeError: «x» is (not) «y»
- The JavaScript exception is (not) y» occurs when there was an unexpected type.
- SyntaxError: function statement requires a name
- The JavaScript exception «function statement requires name» occurs when there is in code that There is a function statement in code that requires name.