JavaScript Semicolons: Automatic Semicolon Insertion Rules and Traps
When JavaScript inserts semicolons for you and when it doesn't: the three ASI rules, the five characters that join lines together ( [ ` / + -, the return-on-its-own-line bug, postfix ++, arrows, class fields, and how ESLint and Prettier make the semicolon debate irrelevant.
kvi5hnuCode Sprout team member9 min readOn this page
Most JavaScript statements end with a semicolon, but you can leave many of them out: the engine inserts the missing ones. This feature is called automatic semicolon insertion (ASI). It's why both of these styles are common and both work:
const greeting = "hello";
console.log(greeting);
const greeting = "hello"
console.log(greeting)
ASI isn't "every line break is a semicolon", though. The rules are specific, and the cases where they surprise you are classic interview questions and real production bugs. This article explains the rules precisely, shows every trap with runnable code, and ends with the practical answer to "should I use semicolons?".
The rules
The specification describes ASI as error recovery. While parsing, the engine inserts a semicolon only in these situations:
- The next token can't continue the statement, and there's a line break before it. The engine reads as far as it can; if the next token would be a syntax error and it's on a new line, a semicolon is inserted before it.
- The next token is
}. A semicolon is inserted before a closing brace:if (ok) { return 1 }is fine. - The input ends. A missing semicolon at the very end of the program is added.
And there are restricted productions, places where a line break is always treated as the end of the statement, even though the next line could continue it:
- after
return,throw,break,continueandyield(and before the value or label that follows), - before postfix
++and--, - between an arrow function's parameters and its
=>, - after
asyncwhen it starts an async function or arrow.
Two things ASI never does: it never inserts a semicolon inside the header of a for loop, and it never inserts one if the result would be an empty statement.
Here's rule 1 in action. This looks like nonsense, but it's legal:
let a
a
=
3
console.log(a)
3
The first line break becomes a semicolon because let a a can't be parsed. The second doesn't, because a = 3 can continue across lines, so the engine keeps reading. The program is let a; a = 3; console.log(a);.

The danger: lines that continue the previous one
Rule 1 means a line break is not a semicolon when the next line can continue the statement. Five characters at the start of a line allow that: (, [, `, /, and + or -. When a line starts with one of them and the previous line has no semicolon, the two lines are joined.
A line starting with (
const base = 10, adjust = 5
try {
const total = base + adjust
(1 + 2).toString()
console.log(total)
} catch (err) {
console.log(err.name + ": " + err.message)
}
TypeError: adjust is not a function
The engine read base + adjust(1 + 2).toString(), a function call on adjust. This comes up with immediately invoked functions, which start with (.
A line starting with [
const colors = ["red", "green"]
try {
const first = colors
["blue", "gold"].forEach(c => console.log(c))
} catch (err) {
console.log(err.name + ": " + err.message)
}
TypeError: Cannot read properties of undefined (reading 'forEach')
This became colors["blue", "gold"].forEach(...). Inside brackets, the comma is the comma operator, so the index is "gold", and colors["gold"] is undefined. Starting a line with an array literal is common when you destructure, as in [a, b] = [b, a] to swap two variables.
A line starting with a backtick
```javascript runnable title="joins with the previous line" const prefix = "id" try { const id = prefix row-7`
console.log(id)
} catch (err) {
console.log(err.name + ": " + err.message)
}
```text
TypeError: prefix is not a function
A template literal right after an expression is a tagged template: a function call with special arguments (part 14 covers tags). So this tried to call prefix as a tag function.
A line starting with / or -
These don't throw, which makes them worse: they silently compute something else.
const g = 2, size = 8
const half = size
/2/g
console.log(half) // size / 2 / g, not a regex
let score = 5
-1
console.log(score) // score = 5 - 1
2
4
The opposite danger: return on its own line
The restricted productions cut statements short even when you didn't want them to. The most famous case:
function settings() {
return
{
theme: "dark"
}
}
console.log(settings())
undefined
A line break after return always ends the statement, so this is return; followed by an unreachable block. The function returns undefined. The fix is to start the value on the same line as return:
function settings() {
return {
theme: "dark",
};
}
If the value is long, wrap it in parentheses that start on the return line: return ( on the first line, the expression below, and ); at the end. This is the standard style for returning multi-line JSX in React.
throw has the same rule, but because throw without an expression is meaningless, the engine reports an error instead of silently doing something:
try {
eval("function check() { throw\n new Error('bad input') }")
} catch (err) {
console.log(err.name + ": " + err.message)
}
SyntaxError: Illegal newline after throw
Other restricted places
Postfix ++ and -- must be on the same line as their operand. Otherwise they attach to the next line as prefix operators:
let p = 1, q = 1
p
++
q
console.log(p, q) // the ++ applied to q, not p
1 2
Arrow functions: the => must be on the same line as the parameters. const double = x followed by => x * 2 on the next line is a SyntaxError.
Class fields have their own trap, because a field declaration is like a statement inside the class body:
try {
class Box {
width = 1
["height"] = 2
}
new Box()
} catch (err) {
console.log(err.name + ": " + err.message)
}
TypeError: Cannot create property 'height' on number '1'
The two lines were read as width = 1["height"] = 2. Computed field names like ["height"] (and generator methods starting with *) need a semicolon on the line before them.
Should you write semicolons?
Both styles are used by large, professional codebases. The facts:
- With semicolons (Airbnb, Google, most TypeScript projects, and this course), you only have to remember the restricted productions, mainly "never break a line right after
return". - Without semicolons (the "standard" style and many Node.js projects), you also have to remember the five characters
( [ ` / + -. The convention is a defensive semicolon at the start of such a line:;[a, b] = [b, a].
let left = "L", right = "R"
;[left, right] = [right, left]
console.log(left, right)
R L
The real answer is: let tools decide. A formatter such as Prettier rewrites your code in one consistent style, adding or removing semicolons (its semi option) and inserting defensive semicolons where needed. A linter such as ESLint catches the dangerous cases: the rule no-unexpected-multiline (in its recommended set) flags lines that are joined in surprising ways, and no-unreachable flags the code after a bare return. With both in place, the debate is purely about taste. Part 17 shows how to set them up.
Common questions
Does a missing semicolon make code slower?
No measurable difference. ASI happens once while parsing, and the result is identical to code with explicit semicolons.
Is ASI the reason return on its own line returns undefined in every language?
No, it's specific to JavaScript's grammar. In C or Java, return followed by a newline and an expression returns that expression, because newlines mean nothing there. JavaScript's restricted productions make the line break significant.
Can the for (;;) semicolons be left out?
No. ASI never inserts the two semicolons in a for loop's header, so for (let i = 0 followed by a newline and i < 3 is a SyntaxError.
Why do some people put a semicolon at the start of files?
When files are concatenated (older build setups did this), a file starting with ( could join the last line of the previous file. A leading ; guards against that. Modern bundlers wrap modules safely, so it's rarely needed today.
Summary
- ASI inserts a semicolon at a line break only when the next token can't continue the statement, before
}, and at the end of input. - A line starting with
(,[,`,/,+or-can continue the previous line, causing calls, indexing, tagged templates or arithmetic you didn't intend. - After
return,throw,break,continueandyield, a line break always ends the statement, soreturnfollowed by a newline returnsundefined. - Postfix
++/--and the arrow=>must stay on the same line as their operand or parameters. Class fields before a computed name need a semicolon. - Pick a style, enforce it with Prettier, and turn on ESLint's
no-unexpected-multiline.
Practice Questions
A function body is return on one line and 1 + 2; on the next. What does the function return?
Answer
undefined. The line break after return ends the statement, and 1 + 2; is unreachable.
The line const n = 3 is followed by the line [1, 2].forEach(console.log). How do you fix it without adding semicolons at line ends?
Answer
Put a defensive semicolon at the start of the second line: ;[1, 2].forEach(console.log). Without it, the code reads as 3[1, 2].forEach(...), which tries to call forEach on undefined.
Which of these line starts can join with the previous line: (, [, {, `, /, -, +, .?
Answer
All of them except {. A { at the start of a line after a complete statement begins a block. . also joins, which is why method chains like promise on one line and .then(...) on the next work. That case is intended and harmless.
Why does the code let x = 1 followed by ++ on its own line and x on the next one set x to 2 instead of throwing?
Answer
Postfix ++ can't follow a line break, so the engine ends the first statement after 1. The ++ then becomes a prefix operator applied to x on the next line: let x = 1; ++x;.
Your team doesn't use semicolons. Which ESLint rule catches most accidental line joins?
Answer
no-unexpected-multiline, which is in ESLint's recommended configuration. It reports lines that start with (, [, ` or a regex-like / and are joined to the previous expression.
Review quiz
You've finished Parts 1 and 2. Check your understanding with the Getting Started and Lexical Structure review quiz: 20 questions on ECMAScript and TC39, running code, the language tour, comments, literals, identifiers, Unicode and semicolons.
Previous: Unicode in JavaScript Source Code: Escapes, Normalization and Invisible Characters
Next: JavaScript Types and Values: Primitives, Objects and the typeof Operator

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.