Uncaught exception syntax error unexpected token

Если вылезла ошибка «Uncaught SyntaxError: Unexpected token», скорее всего, вы пропустили скобку, кавычку, запятую или что-то подобное.

Когда встречается. Допустим, вы пишете цикл 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

Когда интерпретатор не может обработать скрипт и выдаёт ошибку, он обязательно показывает номер строки, где эта ошибка произошла (в нашем случае — в первой же строке):

Интерпретатор обязательно показывает номер строки, где произошла ошибка Uncaught SyntaxError: Unexpected token

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

Строка с ошибкой Uncaught SyntaxError: Unexpected token

По этому фрагменту сразу видно, что браузеру не нравится слово 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);

Have a JavaScript Unexpected Token Error? Check Your Syntax

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.

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:

// 1
var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}

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:

// CHROME
Uncaught SyntaxError: Unexpected token )

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

var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}

try {
var name = «Bob»;
if (name === «Bob») {
console.log(`Whew, it’s just ${name}`);
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:

// CHROME
Uncaught SyntaxError: Unexpected token 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.

Similar to other programming languages, JavaScript has its own syntax. The error “Uncaught SyntaxError: Unexpected token” shows that your code does not match the JavaScript syntax. It could be due to some typos in your code, a mistake when including a JavaScript file into HTML, or a wrong HTML in JavaScript code.

The reason for the error “Uncaught SyntaxError: Unexpected token”

JavaScript has its own syntax for literals, variables, operators, expressions, keywords, and comments. When running your code, the JavaScript runtime tries to parse the code based on the JavaScript syntax. When it cannot do, it throws an error “Uncaught SyntaxError: Unexpected token” with the position where the error occurs. Because it is a syntax error, there are many situations that can cause the error. Usually, it is due to you having an extra or missing a character or punctuation. Another reason is that you accidentally put some HTML code in your JavaScript code in the wrong way. You can reproduce the error with this example. You can easily see that I have an extra close bracket ‘)’, which causes the error.

Example code:

if (true)) {
    console.log('It is true');
} 

Output:

if (true)) {
         ^
SyntaxError: Unexpected token ')'

Example 1: Invalid syntax causes the error

There are many ways that your code has an invalid syntax that cause the error. Here I have an example in that I missed the open and close brackets of the if condition.

Example code:

let a = 1;
let b = 2;
let c = 3;

if (a + b == c) || (a == c) {
    console.log('a is ok');
} 

Output:

if (a + b == c) || (a == c) {
                ^^
SyntaxError: Unexpected token '||'

The error message will also show which is the unexpected token so that you can easily fix this error. You can also avoid invalid syntax in your code by using a suitable JavaScript snippet extension for your code editor, such as Visual Studio Code, Sublime Text, Atom,…

Example 2: Include a file that is not JavaScript to the script tag

Another common mistake that causes the error is including something that is not a valid JavaScript file in the script tag, maybe it is an HTML file.

Example code:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Page 1</title>
    <script src="index.html"></script>
</head>

<body>
    Some content!
</body>

</html>

Output:

Uncaught SyntaxError: Unexpected token '<' (at index.html:1:1)

When you load the HTML code above in your browser, you will get the error in the console. Of course, to fix this error, you need to specify the right path to the JavaScript file that you want to use.

Example 3: Invalid HTML code in JavaScript code

Sometimes, you have some HTML code in your JavaScript code, for example, when you want to set the innerHTML value for an element. Make sure you use your HTML code as a string by putting it in the quotes or you will get a syntax error.

Example code:

let message = document.getElementById("message");

// This's right
message.innerHTML = '<div>Message content</div>'; 

// This cause an error
message.innerHTML = <div>Message content</div>; 

Output:

message.innerHTML = <div>Message content</div>; 
                    ^
SyntaxError: Unexpected token '<'

Summary

In this tutorial, I have some examples to show you how to solve the error “Uncaught SyntaxError: Unexpected token” in JavaScript. You need to make sure your code has valid JavaScript syntax. Also, pay attention to having the right code when you use JavaScript with HTML.

Maybe you are interested in similar errors:

  • Uncaught SyntaxError Unexpected end of input
  • Unexpected token u in JSON at position 0
  • unexpected token o in json at position 1 error in js
  • Cannot read properties of undefined

Hello, I’m Joseph Stanley. My major is IT and I want to share programming languages to you. If you have difficulty with JavaScript, TypeScript, C#, Python, C, C++, Java, let’s follow my articles. They are helpful for you.


Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: JavaScript, TypeScript, C#, Python, C, C++, Java

Doctype html unexpected token: The “Uncaught SyntaxError: Unexpected token” error can occur for a variety of reasons, including:

  • Using a <script /> tag that leads to an HTML file rather than a JS file.
  • Receiving an HTML response from a server where JSON is expected,
  • Having a <script /> tag that leads to the wrong path.
  • When your code is missing or contains extra brackets, parenthesis, or commas.
  • When you forgot to close the <script />tag.

Let us see some of the cases where the “Uncaught SyntaxError: Unexpected token” error Occurs

Cases where the “Uncaught SyntaxError: Unexpected token” error Occurs

Example1

Unexpected token js: Below is an example of an error: our script tag points to a html file rather than a JS file.

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <!-- Here script tag is pointing to an html file instead of JS file 
    Hence Uncaught SyntaxError: Unexpected token '<' occurs-->
    <script src="index.html"></script>
  </body>
</html>

NOTE:

Check that any script tag you use lead to a valid path, and try to rename all your files
using just lowercase characters. 
If the file name contains uppercase letters or special characters, the error may occur.

Example2

Unexpected token doctype: The other common cause of the “Uncaught SyntaxError: Unexpected token” is when we forget to close a script tag.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />

    <!-- Here we forgot to close the script tag, hence 
    Uncaught SyntaxError: Unexpected token '<' occurs -->
    <script
      console.log("Uncaught SyntaxError: Unexpected token '<'");
    </script>
  </head>

  <body></body>
</html>
  • When attempting to parse JSON data, the error is also generated if you make an http request to a server and receive an HTML response.
  • To solve this we can use console.log. The response you receive from your server and ensure it is a proper JSON string free of HTML tags.
  • Alternatively, you can open your browser’s developer tools, navigate to the Network tab, and inspect the response.

Example3: index.js (Giving another extra curly brace)

// Create a function say multiply whict accepts two numbers
// as arguments and returns the multiplication result
function multiply(x, y) {
  // Multiply the above passed two numbers and return the result
  return x * y;
}}

Output:

}}
^

SyntaxError: Unexpected token }
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here we gave another extra curly brace, hence SyntaxError: Unexpected token } occured

These syntax errors are difficult to spot, but an useful tip is:

  • If you receive the “Uncaught SyntaxError: Unexpected token ‘<‘” (ovserve the ‘<‘) error, you are most likely attempting to read HTML code that begins with ‘<‘.
  • If your error message comprises a curly brace, parenthesis, comma, colon, etc., you most certainly have a SyntaxError, which occurs when your code has an additional or missing character.

Example4: index.js (Giving colons two times(::) instead of once(:))

// Create an object and store it in a variable
const obj = {
  // Here we gave colons two times(::) instead of once(:) to separate the key-value pairs
  // so,the SyntaxError: Unexpected token : occurs
  Website:: "Btechgeeks",
}

Output:

Website:: "Btechgeeks",
^

SyntaxError: Unexpected token :
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here we gave colons two times(::) instead of once(:) to separate the key-value pairs 
so,the SyntaxError: Unexpected token : occurs

Example5: index.js (Giving an extra comma)

// Create an object and store it in a variable
const obj = {
  // Here we gave an extra comma(,) 
  // Hence the SyntaxError: Unexpected token occurs
  Website: "Btechgeeks",,
}

Output:

Website: "Btechgeeks",,
^

SyntaxError: Unexpected token ,
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Fixing the “Uncaught SyntaxError: Unexpected token” Error

To resolve the “Uncaught SyntaxError: Unexpected token” error, make the following changes:

  • We should not have a <script/> tag that points to an HTML file, instead of a JS file.
  • Instead of requesting an HTML file from a server, you are requesting JSON.
  • There is no <script/> tag pointing to an incorrect path.
  • There must be no missing or excessive brackets, parenthesis, or commas.
  • Do not forget to close a <script tag.

Понравилась статья? Поделить с друзьями:
  • Uncaught exception error spawn
  • Uncaught exception error ehlo not accepted from server
  • Uncaught exception error cannot find module
  • Uncaught error перевод
  • Uncaught error vk not initialized please use vk init