Sometimes, we may run into the ‘SyntaxError: Unexpected token’ when we’re developing JavaScript apps.
In this article, we’ll look at how to fix the ‘SyntaxError: Unexpected token’ when we’re developing JavaScript apps.
Fix the ‘SyntaxError: Unexpected token’ When Developing JavaScript Apps
To fix the ‘SyntaxError: Unexpected token’ when we’re developing JavaScript apps, we should make sure we’re writing JavaScript code that’s syntactically valid.
Different unexpected token errors that may be thrown include:
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 instance, we should make sure we aren’t adding trailing commas when we’re chaining expressions:
for (let i = 0; i < 5,; ++i) {
console.log(i);
}
We have:
i < 5,;
which has a comma before the semicolon. This is invalid syntax.
Instead, we should write:
for (let i = 0; i < 5; ++i) {
console.log(i);
}
which removed the extra comma.
We should also make sure that we have corresponding closing parentheses for any opening parentheses.
For example, instead of writing:
function round(n, upperBound, lowerBound){
if(n > upperBound) || (n < lowerBound){
throw 'Number ' + String(n) + ' is more than ' + String(upperBound) + ' or less than ' + String(lowerBound);
}
}
We write:
function round(n, upperBound, lowerBound) {
if (n > upperBound || n < lowerBound) {
throw (
"Number " +
String(n) +
" is more than " +
String(upperBound) +
" or less than " +
String(lowerBound)
);
}
}
which removes the extra parentheses from if
boolean expression.
Conclusion
To fix the ‘SyntaxError: Unexpected token’ when we’re developing JavaScript apps, we should make sure we’re writing JavaScript code that’s syntactically valid.