2020-04-09

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?

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

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

- a line
*begins*with a round bracket - a line
*begins*with a square bracket - a line
*bugins*with a negative number

variable (function () {})()

is

variable(function () {})()

and

variable [0]

is

variable[0]

and

variable -1

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

- 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
- 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