SyntaxError: Unexpected token in JS and Python - 10 Common Cases and Fast Fixes

SyntaxError: Unexpected token in JS and Python - 10 Common Cases and Fast Fixes

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

  1. Mismatched quotes
    "hello' - fix to "hello" or 'hello'.
  2. Mismatched brackets
    arr[0} - fix to arr[0].
  3. Trailing commas in JSON
    JSON does not allow trailing commas. Remove them.
  4. Accidental template delimiters
    Backticks in JS require proper interpolation. Verify ${expr}.
  5. Stray characters
    Invisible non-ASCII characters can sneak in. Re-type the line.
  6. Operator misuse
    Assignment vs comparison. In JS use === for comparison.
  7. Python indentation
    Consistent spaces, not tabs. Blocks must align.
  8. Unclosed strings or comments
    Close all string and comment delimiters.
  9. Bad JSON.parse input
    Validate JSON externally or use try and catch and show a helpful message.
  10. 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

Image credit: Photo by Polina Zimmerman: https://www.pexels.com/photo/black-smartphone-displaying-error-3747139/

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.