Unexpected token
JavaScript compiler encountered a symbol or character it did not expect in the active code grammar context.
Usually happens because:
- ☑ Stray closing brace/parenthesis
- ☑ Malformed JSON string
- ☑ Incorrect object key separator
🔍 Quick Checklist:
📊 Where this usually happens (estimated occurrence)
What is Unexpected token?
This error is thrown during parsing when the JavaScript engine encounters a character or symbol (like a brace, parenthesis, comma, or semi-colon) that does not match the syntax rules of the language at that specific position. The engine cannot continue parsing the code layout and halts compilation.
Common Causes
- Accidental extra or stray closing characters (like } or ).
- Using newer JavaScript syntax (e.g. optional chaining or nullish coalescing) in older browser engines without transpilation.
- Malformed JSON parsing in JSON.parse().
Common Mistakes
- Typing extra parentheses or braces when nesting deep function calls or loop brackets.
- Passing unescaped characters inside JSON strings.
How to Fix
Framework-Specific Examples
JSON parsing requires double quotes for keys and string values. Single quotes throw unexpected token errors.
try {
// Throws: Unexpected token ' in JSON
JSON.parse("{'name':'John'}");
} catch (err) {
console.error(err.message);
}Server Configuration Examples
Checking tokens.
# Handled at parser layerBest Practices
- Use modern IDE formatters (like Prettier) that auto-align code blocks.
- Enable lint checking rules to flag stray symbols.
Frequently Asked Questions (FAQ)
Q: What is a token?
A token is a single atomic unit of code (like a keyword, variable name, number, string, or punctuation symbol) that the parser reads to understand your program.
Q: Why does JSON.parse trigger unexpected token?
Because the string you passed is not valid JSON. JSON requires double quotes around keys and string values, and rejects trailing commas.
Q: Does this happen at runtime?
No. In standard JavaScript, syntax parsing occurs before runtime execution begins. However, functions like `eval()` or `JSON.parse()` can raise it at runtime.
Q: How do I debug mismatched braces?
Use an editor like VS Code that highlights matching brackets, or run code formatters (like Prettier) which fail with helpful lines if brackets mismatch.