Optional Semicolons

Like many programming languages, JavaScript uses the semicolon (;) to separate statements from each other. In JavaScript, you can usually omit the semicolon between two statements if those statements are written on separate lines.

Consider the following code. Since the two statements appear on separate lines, the first semicolon could be omitted:

a = 3;
b = 4;

Written as follows, however, the first semicolon is required:

a = 3; b = 4;

Note that JavaScript does not treat every line break as a semicolon: it usually treats line breaks as semicolons only if it can’t parse the code without the semicolons. More formally, JavaScript interprets a line break as a semicolon if it appears after the return, break, or continue keywords, or before the ++ or -- operators, or if the next nonspace character cannot be interpreted as a continuation of the current statement. 

These statement termination rules lead to some surprising cases. This code looks like two separate statements separated with a newline:

var y = x + f
(a+b).toString()

But the parentheses on the second line of code can be interpreted as a function invocation of f from the first line, and JavaScript interprets the code like this:

var y = x + f(a+b).toString();
  • Updated
    Aug 24, 2014
  • Views
    2,502