Rules for Using Semicolons

30 October 2020, 11:32 am by antelove19


Sources:

OReilly 1


In this section, we examine how semicolons are used in JavaScript. The basic rules are:

  • Normally, statements are terminated by semicolons.
  • The exception is statements ending with blocks.

Semicolons are optional in JavaScript. Missing semicolons are added via so-called automatic semicolon insertion (ASI; see “Automatic Semicolon Insertion” on page 59).

However, that feature doesn’t always work as expected, which is why you should always include semicolons.


No Semicolon After a Statement Ending with a Block


The following statements are not terminated by semicolons if they end with a block:

  • Loops: for, while (but not do-while)
  • Branching: if, switch, try
  • Function declarations (but not function expressions)

Here’s an example of while versus do-while:

while ( a > 0 ) {
    a--;
} // no semicolon

do {
    a--;
} while ( a > 0 );


And here’s an example of a function declaration versus a function expression. The latter is followed by a semicolon, because it appears inside a var declaration (which is terminated by a semicolon):

function foo() {
    // ...
} // no semicolon

var foo = function () {
    // ...
};

  1. OReilly Ebook, "OReilly.Speaking.JavaScript.(2014)", page 57 




Video not yet
0 comment