javascript semicolons

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

incomplete expressions

this is how semicolon insertion works practically. 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
var a = // incomplete because =
  aaaaaaaaaaaaaaaaaaaaa //incomplete because ||
  || bbbbbbbbbbbbbbbbbbbbbbbb // incomplete
  || cccccccccccccccccccccccc //complete
var b = 3

non-obvious cases

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

  1. a line begins with a round bracket
  2. a line begins with a square bracket
  3. a line bugins with a negative number
(function () {})()


variable(function () {})()







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

avoid the non-obvious cases

  1. if a line starts with an opening round or square bracket, put a semicolon before it
  2. if a line starts with a minus, and it is the beginning of a new expression, use round brackets around the expression
  3. use semicolons between multiple separate expressions on one line


;(function () {

;[1, 2]

;(-1 == create_result() || do_something())

for(var a = 1; i < 1; i+=1){}

apart from these situations, dont use semicolons. these are only 3-4 fixed patterns to look out for and they all derive from the same single principle - incomplete expressions. knowing and applying these rules is simpler than to ignore them and striving to set semicolons everywhere without forgetting one. which also creates syntactic noise. furthermore, everything to look out for is always the first character of a line. this is easier than checking the multi-length ending of every line for a missing semicolon

further reading

semicolons in javascript are optional