← All Articles

SyntaxError: Unexpected Token in JavaScript — Causes & Fixes

What Does This Error Mean?

JavaScript's parser hit a character it didn't expect at that position. The "token" is the offending character — could be a missing bracket, a stray comma, or invalid JSON syntax.

Most Common Causes

  • Missing or extra brackets/braces: { "a": 1, } (trailing comma in JSON)
  • Parsing non-JSON as JSON: JSON.parse("undefined")
  • Using reserved words as variables: let class = 'math'
  • Missing await: const data = fetch(url) then using data as object
  • File encoding issues (BOM characters)

How to Fix It

1. Check the column number

// Error says "Unexpected token } in JSON at position 42"
// Count to character 42 in your JSON string
// Usually a trailing comma or missing quote

2. Validate JSON before parsing

try {
  const data = JSON.parse(responseText)
} catch (e) {
  console.log('Invalid JSON:', responseText.slice(0, 100))
}

3. Common fix: remove trailing commas

// Bad (valid JS, invalid JSON)
{ "name": "test", }

// Good
{ "name": "test" }