A couple of winter solstice notes on JavaScript from my recent reading.
The first is on automatic semicolon insertion. You don’t have to use semicolons to write JavaScript, but if you don’t, some rules apply. The first rule is pretty simple: when processing a statement, the parser includes everything until it encounters a semicolon or an “offending token” that cannot be part of the statement. If this offending token is a line termination, end of input or a }
, a semicolon is added.
For example,
let x = 6
becomes
let x = 6;
It gets weird if you start a line with a (
or [
, so don’t do that if you don’t want to be confused about where the semicolon might be added.
There is a second semicolon rule where a semicolon is inserted after a nonlinear control flow statement (break
, continue
, return
, throw
or yield
) that is immediately followed by a line termination.
So,
return
x + 44;
adds a semicolon after the return
and the last statement isn’t run.
I’m in the habit of using semicolons as a line termination, so I’ll make that my standard but it’s good to know the rules. Configuring a linter is probably helpful for avoiding these sorts of issues.