SyntaxError: Unexpected token in JS and Python - 10 Common Cases and Fast Fixes
Share
TL;DR: The parser tripped on a character or structure it did not expect. Fix mismatched quotes and brackets, trailing commas in JSON, stray characters, and indentation issues. Always check the character just before the one reported.
Why parsers fail
Both languages tokenize input and expect certain tokens to follow. When you break structure, the parser raises a SyntaxError. The reported location often points to the token after the real problem.
Top 10 causes with short fixes
-
Mismatched quotes
"hello'- fix to"hello"or'hello'. -
Mismatched brackets
arr[0}- fix toarr[0]. -
Trailing commas in JSON
JSON does not allow trailing commas. Remove them. -
Accidental template delimiters
Backticks in JS require proper interpolation. Verify${expr}. -
Stray characters
Invisible non-ASCII characters can sneak in. Re-type the line. -
Operator misuse
Assignment vs comparison. In JS use===for comparison. -
Python indentation
Consistent spaces, not tabs. Blocks must align. -
Unclosed strings or comments
Close all string and comment delimiters. -
Bad JSON.parse input
Validate JSON externally or use try and catch and show a helpful message. -
Copy-paste artifacts
Replace curly quotes with straight quotes.
JSON rules at a glance
- Keys and strings must use double quotes.
- No comments.
- No trailing commas.
Build steps and minifiers
Sometimes the error originates in generated code. Inspect the original source map and fix the source, not the bundle.
Quick checklist
- Look one character to the left.
- Match every opening with a closing token.
- Validate JSON with an external tool.
- Use a linter to catch common mistakes before running.
FAQ
Why does the error point to the next token
The parser only realized there was a problem when it met a token that could not follow the previous one. The true bug is often right before the pointer.
Is JSON the same as JS object literal
No. JSON is stricter. For example, JSON requires double quotes and does not allow trailing commas.
Cast this in your project
- SyntaxError T-shirt for the linter fans.
- JavaScript Flashcards to practice clean syntax patterns.
Image credit: Photo by Polina Zimmerman: https://www.pexels.com/photo/black-smartphone-displaying-error-3747139/