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.
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
three cases may cause unintuitive parsing results:
(
[
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.
;
if a line begins with (
or [
.;(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.