Have a JavaScript Unexpected Token Error? Check Your Syntax

Today, we are discussing the Unexpected Token Error within our JavaScript Error Handling series. The Unexpected Token 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 in JavaScript 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 error 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 Unexpected Token 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, Unexpected Token errors are 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 Unexpected Token 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 April 2022.

Monitor Your App Free for 30 Days

Discover the power of Airbrake by starting a free 30-day trial of Airbrake. Quick sign-up, no credit card required. Get started.