How to Fix SyntaxError: Unexpected token in JavaScript
In this tutorial, you'll learn about How to Fix SyntaxError: Unexpected token in JavaScript. We cover key concepts, practical examples, and best practices.
The Problem
JavaScript throws SyntaxError: Unexpected token when the parser encounters a character it does not expect at that position, usually from missing brackets, mismatched quotes, trailing commas, or stray operators.
Quick Fix
Step 1: Check for mismatched brackets
A missing closing brace causes the parser to misinterpret the next character:
const obj = { name: 'Alice'; };
SyntaxError: Unexpected token ';'
Replace the semicolon inside the object with a comma:
const obj = { name: 'Alice' };
console.log(obj);
{ name: 'Alice' }
Step 2: Fix missing closing parentheses
Each opening parenthesis must have a matching closing one:
console.log('hello';
SyntaxError: Unexpected token ';'
Add the missing closing parenthesis:
console.log('hello');
hello
Step 3: Remove trailing commas in JSON
JSON does not allow trailing commas after the last property:
const data = '{"name": "Alice", "age": 30,}';
JSON.parse(data);
SyntaxError: Unexpected token '}'
Remove the trailing comma:
const data = '{"name": "Alice", "age": 30}';
JSON.parse(data);
{ name: 'Alice', age: 30 }
Step 4: Check for stray operators
An operator without operands causes syntax errors:
const x = 5 +
const y = 3;
SyntaxError: Unexpected token 'const'
Place the operator on the same line as its operands:
const x = 5 + 3;
console.log(x);
8
Prevention
- Use a code editor with bracket matching and syntax highlighting.
- Run
npx eslint --fixbefore committing code. - Validate JSON with
jq . file.jsonbefore parsing in code. - Use Prettier for automatic formatting on save.
Common Mistakes with syntaxerror
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro