Semicolons
Learn about semicolons in JavaScript, including how automatic insertion works and the impact on code readability.
Learn about semicolons in JavaScript, including how automatic insertion works and the impact on code readability.
Semicolons end statements in JavaScript. They’re technically optional because JavaScript has Automatic Semicolon Insertion (ASI) — but that mechanism has edge cases worth knowing about.
const name = "Reza";console.log(name);These two statements are separated by semicolons. The parser knows where one ends and the next begins.
JavaScript inserts semicolons automatically in most places where they’re missing. This works reliably for the vast majority of code:
const name = "Reza"; // ASI adds ; hereconsole.log(name); // ASI adds ; hereASI fails when a line starts with (, [, /, +, or -:
const a = 1;const b = (2)[(a, b)].forEach(console.log);// Interpreted as: const b = 2[a, b].forEach(...)// TypeErrorFix:
const a = 1;const b = 2;[a, b].forEach(console.log);The two camps:
Both are valid. What’s not valid is mixing randomly within a project. Pick one, use a linter (ESLint + Prettier), and stop thinking about it.
Most modern codebases use Prettier which enforces semicolons (or not) automatically. Let the tool decide.