What does unexpected token mean in JavaScript?
Short answerIt means the JavaScript parser found a character or word it didn't expect at that point in the code. Common causes include missing punctuation, mismatched brackets, or using reserved words incorrectly.
Common triggers
The error message usually includes the token and its location. For example, 'Unexpected token )' means the parser found a closing parenthesis where it expected something else, often due to an extra or missing bracket.
Other frequent causes are missing commas in object or array literals, using a reserved word as an identifier, or forgetting to close a string or template literal.
- Mismatched parentheses, brackets, or braces
- Missing comma between object properties or array elements
- Unclosed string, template literal, or comment
- Using a reserved word like 'class' or 'function' as a variable name
- Incorrect use of arrow functions or async/await syntax
How to debug it
Check the line number in the error message. The actual problem is often on that line or the line before. Look for obvious syntax issues like missing commas or extra brackets.
Use your editor's bracket matching and syntax highlighting. If the error is vague, try commenting out sections of code to isolate the problem.
- Read the error message carefully; it often names the unexpected token
- Use a linter like ESLint to catch syntax errors before running
- Check for missing commas in multi-line object or array declarations
- Ensure all strings and template literals are properly closed
Common mistakes
- Assuming the error is always on the reported line; it can be earlier.
- Ignoring that a missing comma in an object can cause an 'Unexpected token' error on the next line.
- Thinking that 'Unexpected token' only applies to punctuation; it can also be a reserved word.
