How do I fix a missing semicolon error in JavaScript?
Short answerJavaScript often inserts semicolons automatically, but when it guesses wrong you get an error. Add a semicolon at the end of the statement the error points to, or just before the line where the error is reported.
Why it happens
JavaScript has Automatic Semicolon Insertion (ASI), which adds semicolons in many cases. But ASI doesn't always guess correctly, especially when a line starts with (, [, /, +, or -.
When ASI fails, you get a SyntaxError like 'Unexpected token' or 'Missing semicolon'. The error message usually points to the line after the one that's actually missing a semicolon.
- A line ends with a return, throw, break, or continue and the next line starts with a value
- A line starts with an opening parenthesis or bracket, causing the previous line to be treated as a function call
- You wrote two statements on one line without a semicolon between them
How to fix it
Look at the line just before the reported error line. Add a semicolon at the end of that line. If the error persists, check the line before that, and so on.
If you use a linter like ESLint with the 'semi' rule, it will flag missing semicolons. Many style guides recommend always using semicolons to avoid ASI pitfalls.
- Add a semicolon at the end of every statement
- Avoid starting a line with ( or [ unless you intend to continue the previous expression
- Use a code formatter like Prettier to automatically insert semicolons
- Enable ESLint's semi rule to catch missing semicolons during development
Common mistakes
- Thinking JavaScript never needs semicolons; ASI can fail in edge cases.
- Adding a semicolon on the error line instead of the previous line.
- Believing that a missing semicolon always causes an immediate error; sometimes it silently changes behavior.
