January 08, 2024•JavaScript
Why is my JavaScript breaking with 'Unexpected token' errors?
javascriptsyntax-errorssemicolons
The Answer: You're probably missing a semicolon somewhere! 😅
JavaScript has something called "Automatic Semicolon Insertion" (ASI), but it doesn't always work the way you expect. Sometimes a missing semicolon can cause the next line to be interpreted as part of the previous statement.
Common scenarios:
// This breaks:
let a = 5
let b = 10
[1, 2, 3].forEach(console.log) // Error!
// JavaScript sees this as:
let a = 5let b = 10[1, 2, 3].forEach(console.log)
How to avoid this:
- Use a linter like ESLint with semicolon rules
- Be consistent - either always use semicolons or never use them
- Use Prettier to automatically format your code
- Learn the ASI rules if you want to go semicolon-free
My recommendation: Just use semicolons. It's clearer, more explicit, and prevents these weird edge cases. Your future self will thank you! 🙏