2023-01-25

javascript semicolons

semicolons are optional, as defined by the ecma standard, and the correct behaviour is implemented in all modern browsers starting from at least internet explorer 3(!) upwards. there is no browser compatibility issue. the only question that needs to be answered to determine if a semicolon is necessary is: is the expression complete?

incomplete expressions

this is how semicolon insertion works: if the current expression is not terminated, javascript looks ahead into following lines to see if the current expression is continued. if it is, it adds the following expressions to the current one until it is complete.

1     // not complete, because ...
+ 2   // + operator

this makes sense because the user might want to spread long expressions over multiple lines, for example with logical operators like || and &&, long formulas, or with + when joining strings.

var a = // incomplete because =
  aaaaaaaaaaaaaaaaaaaaa // incomplete because of ||
  || bbbbbbbbbbbbbbbbbbbbbbbb // incomplete
  || cccccccccccccccccccccccc // complete
var b = 3

non-obvious cases

there are only three cases that might seem surprising at first:

  • a line begins with a round bracket
  • a line begins with a square bracket
  • a line begins with a negative number
variable
(function () {})()

is the same as

variable(function () {})()

and

variable
[0]

is the same as

variable[0]

and

variable
-1

is equivalent to "variable - 1", because "-" is an operator always, even when attached to a number

avoid the non-obvious cases

  • if a line starts with an opening round or square bracket, put a semicolon before it
  • if a line starts with a minus, and it is the beginning of a new expression, use round brackets around the 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 a = 1; i < 1; i+=1) {}

apart from these situations, do not use semicolons. these are only 3-4 fixed patterns to check for semicolons and they all derive from the same single principle - incomplete expressions. knowing and applying these rules is simpler than to outright ignore them and to strive to set semicolons everywhere without forgetting a single one. semicolons add syntactic noise. furthermore, everything tha has to be looked out for is always the very first character of a line, which is easier to check compared to looking at the last character of every multi-length line for missing semicolons

further reading

semicolons in javascript are optional