skip to content

A JavaScript file written without semicolons starts throwing `TypeError: x is not a function` right after someone adds a line beginning with `(`; why does that happen, and how do you stop it recurring?

level: seniorimportance: should knowfreq 33%

answer

  1. not a semicolon at every newline
  2. three insertion rules
  3. the next token can continue
  4. the previous line gets called
  5. enforce it in tooling

basics

~20 s

No semicolon is inserted, because a line starting with ( can legally continue the previous expression as a call. Insertion needs an offending token or a restricted production. Prefix such lines with a semicolon, and enforce it with a linter.

solid answer

~50 s

Automatic semicolon insertion does not mean a semicolon at every newline. It fires in three cases: a token the grammar does not allow, after a line break or before `}`; the end of input; and a restricted production such as `return`. A line starting with `(` is legal as a continuation, so `const a = b` followed by `(fn)()` parses as `const a = b(fn)()`. `b` gets called, and the error points at code that looks innocent. If `b` happens to be a function, nothing throws and the wrong code runs silently. Lines starting with `[`, a backtick, `+`, `-` or `/` merge the same way. To stop it recurring I make it a tooling decision, not a review habit: either require semicolons, or allow none and enforce a leading `;` on those lines. A linter rule against unexpected multi-line expressions in CI backs up either choice.

code

javascript · 8 lines
javascript
const arr = [10, 20, 30]
let a = 1, b = 2
let c = arr
[a, b] = [b, a]

console.log(a, b); // 1 2
console.log(c);    // [ 2, 1 ]
console.log(arr);  // [ 10, 20, [ 2, 1 ] ]

go deeper

for a junior

Recall that the parser does not add a semicolon at every newline. Know that a line beginning with a parenthesis or a square bracket can attach to the line above it.

for a middle

State the three insertion rules, and contrast a restricted production with a token that can continue the expression. Predict the merged statement for the line starts that join the previous line.

for a senior

Read an error naming the wrong function as a sign of a merge, and read the statement across the break. Know the silent versions, and make the fix a CI rule instead of a review habit.

for a principal

Either semicolon style is defensible, and the costly outcome is having no enforced standard. Choose one, automate it with a formatter and a linter, and end the debate so reviews can spend attention elsewhere.

## The symptom A file that has worked for months starts throwing after a harmless-looking edit: ```javascript const settings = { limit: 5 }; const limit = settings.limit (() => { setup(); })(); ``` The error reads something like `settings.limit is not a function`; the wording varies by engine. The new line looks fine, and the reported name sits on the line above. The cause is that the two lines are **one statement**. ## The three insertion rules **Automatic semicolon insertion (ASI)** repairs token sequences that would otherwise be invalid. It runs in three cases: 1. The parser meets a token the grammar does not allow, and that token is separated from the previous one by at least one line terminator, or the token is `}`. A semicolon goes before it. 2. The input ends and what was read is not a complete program. A semicolon goes at the end. 3. The grammar forbids a line terminator at some position, the **restricted productions**, and one is there. A semicolon goes in at that point. `return`, `break` and postfix `++` are in this group. A line break on its own does nothing. Under rule 1, if the next token **can** continue the current statement, the parser continues it. A `(` after an identifier is a call, so nothing is invalid and rule 1 never applies. ## Which line starts merge | Line starts with | The previous line becomes | Typical result | |---|---|---| | `(` | A function call | `TypeError`, or a silent wrong call | | `[` | A property access | `TypeError`, or a silent wrong value | | Backtick | A tagged template call | `TypeError`, or a silent wrong call | | `+` or `-` | A binary expression | Silent: `const a = 1` then `+2` gives `3` | | `/` | A division | Silent, or a `ReferenceError` or `SyntaxError` | After a complete expression, a line starting with an identifier or a declaration keyword such as `let` is safe: that token cannot continue the expression, so rule 1 fires. ## The silent versions The throwing cases are the easy ones. Harder to find are merges that stay valid: - If the previous expression is a function, `(fn)()` calls it with `fn` as an argument, and execution continues with a wrong value. - `let c = arr` followed by `[a, b] = [b, a]` parses as `let c = arr[a, b] = [b, a]`. A property of `arr` is overwritten, `c` receives the array, and the intended swap never happens. - `const fn = () => 1` followed by `(() => 2)()` makes the second line part of the arrow body, so nothing fails until `fn` is called. ## How to diagnose it 1. Read the statement **across the line break**, starting from the end of the previous line, as the parser does. 2. Check what the reported name holds. If `x is not a function` names something that was never meant to be called, suspect a merge. 3. Look for what changed at the start of the line, and at the end of the previous one. A file concatenated from two sources can create this at the join, when one source ends without a semicolon and the next begins with `(`, which is why older scripts often began with `;(function () { ... })()`. ## The decision a team has to make Both styles work, provided the tool enforces them. Either way this is a standing choice rather than a matter of care in review: - **Semicolons required.** Each statement ends explicitly, so a merge has nothing to work with. One forgotten semicolon is the remaining risk, and a lint rule requiring semicolons may not see it, because the merged code is one valid statement. A formatter re-prints it on one line, which shows up in the diff. Restricted productions still apply, since `return` followed by a newline ends the statement in this style as well. - **Semicolons omitted.** A formatter prefixes the dangerous line starts with `;`, as in `;[1, 2].forEach(run)`. This is a safe style only with that enforcement. By hand it depends on remembering six characters. - **Either way**, run a linter rule against unexpected multi-line expressions in CI. It targets this kind of merge, and it covers code that never reached the formatter. Other cases need a word in the same standard. **Class fields** must end in a semicolon before a generator method or a computed member: `a = 1` followed by `*gen() {}` is a `SyntaxError`, since it reads as multiplication. ASI also never produces an empty statement, nor a separator in a `for` head, so `if (x)` followed by a `const` line fails rather than being repaired, and a three-line `for` head without semicolons does too.

  • If a JavaScript team requires semicolons everywhere, can automatic semicolon insertion still change what a program does?
    Yes. Requiring semicolons largely closes the line-start merges, since statements end explicitly, but restricted productions work regardless of style. `return` followed by a line break still inserts a semicolon, and so does `break` before a label on the next line. The grammar does this during parsing, so the code's style has no say. An unreachable-code lint rule covers that remaining case.
  • Why does `a = 1` followed by `*gen() {}` inside a JavaScript class body fail to parse?
    A `*` on the next line can continue the field's initialiser as a multiplication, so no semicolon is inserted, and the parser reads `a = 1 * gen()`. It then meets `{`, which is not valid there, and reports a `SyntaxError`. Class fields should end with a semicolon, which also protects a following computed member that begins with `[`.
  • Why does the JavaScript parser insert a semicolon after `a = b` before a next-line `++c`, but not before a next-line `(c)`?
    Postfix `++` is a restricted production: the grammar forbids a line terminator before it, so `++` can't attach to `b`, and a semicolon goes in. A `(` has no such restriction and is legal after `b` as a call, so the lines merge into `a = b(c)`. The two cases look alike but fall under different insertion rules.

  • JavaScript adds a semicolon at every line break where the author left one out.
  • A missing semicolon always produces an error you will notice.
  • A line starting with an identifier is just as dangerous as one starting with a parenthesis.
  • Writing semicolons everywhere means insertion can no longer change what a program does.
  • Semicolon-free code cannot be made safe under any tooling.
  • A line starting with a parenthesis always throws, so the failure is easy to see.