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.
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.
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.
The best way to learn how to fix an Unexpected Token error is to go through a couple of examples.
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:
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.
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.
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.