2025-08-16

javascript semicolons

semicolons are optional in javascript, as defined by the ecmascript specification. automatic semicolon insertion (asi) is standardized and consistently implemented in all major engines since the late 1990s. there is no browser compatibility issue.

the only relevant question is whether an expression is syntactically complete. if it is not, the parser continues into subsequent lines until completion.

incomplete expressions

example:

1     // not complete, binary operator follows
+ 2   // continues the expression

this allows multi-line expressions, for instance with ||, &&, +, or long assignments:

var a = // incomplete due to =
  aaaaaaaaaaaaaaaaaaaaa // incomplete due to ||
  || bbbbbbbbbbbbbbbbbbbbbbbb // incomplete
  || cccccccccccccccccccccccc // complete
var b = 3

non-obvious cases

three cases may cause unintuitive parsing results:

  • a line beginning with (
  • a line beginning with [
  • a line beginning with a minus sign

examples:

variable
(function () {})()

parses as:

variable(function () {})()
variable
[0]

parses as:

variable[0]
variable
-1

parses as:

variable - 1

because - can always be an operator, even when directly attached to a number or identifier.

avoiding the non-obvious cases

  • prepend ; if a line begins with ( or [.
  • wrap negative literals in parentheses when starting a new expression.
  • otherwise use semicolons only to separate multiple expressions on the same line.

examples

;(function () {
})()
;[1, 2].foreach()
;(-1 == create_result() || do_something())
for (var i = 0; i < 1; i += 1) {}

outside of these fixed cases, semicolons are unnecessary. these patterns all follow from the same principle: whether the preceding expression is complete. checking only the first character of a new line is sufficient, in contrast to scanning line endings.

further reading

semicolons in javascript are optional