Exceptions to the JavaScript optional semicolon rule

Exceptions to the JavaScript optional semicolon rule

4 min. read

This is part 2 of the article Optional semicolon in JavaScript. If you have not read part 1 of this article, then please click here to read it, after that you be able to fully understand this article.

General rule for semicolon in JavaScript is that "JavaScript interprets line break after a statement as semicolon if it cannot parse the second statement as the continuation of the first statement."

As we discussed in part 1 that below two statements

x = 5 // Statement 1
y = 7; // Statement 2

will be interpreted by JavaScript as

x = 5; y = 7;

That is because JavaScript cannot interpret 5 y so it treats line break as semicolon in this case.

Second example we discussed was

var f = x
(a + b).toLowerCase()

in this case JavaScript will interpret these lines of code as

var f = x(a + b).toLowerCase();

It does not treat line break as semicolon in this case because here second statement can be interpreted as continuation of the first statement.

As we have seen from above two examples that JavaScript follows the rule stated in the beginning of this article.

But there are two exceptions to this general rule.

First exception

First exception involves return, break and continue statements.

These statements are generally used alone but sometimes identifier or some expression is used after these statements.

eg.

return; // Example 1
return true; // Example 2

Rule regarding semicolon for these statements is that

If a line break comes after return, break or continue statement then the line break will always be interpreted as a semicolon.

eg.

return
x

Above two lines will be interpreted as

return; x;

However you probably meant

return x;

So if you are using some expression after these statements then that must appear on the same line after these statements otherwise your code logic will fail.

// Bad practise to write return statement
return
x
// Good practise to write return statement
return x;

Second exception

Second exception involves ++ and -- operators. These operators are used as prefix or postfix operators.

Prefix means: ++ or -- operators will be used before the expression.

eg.

++a;
--b;

Postfix means: ++ or -- operators will be used after the expression.

eg.

a--;
b--;

Rule regarding semicolon for these statements is that

If ++ and -- are to be used as postfix then they must be written on the same line with the expression, if line break is used after the expression it will be interpreted as a semicolon and ++ and -- will be treated as prefix operator for the next lines of code.

eg.

x
++
y;

will be interpreted as

x; ++y;

not as

x++; y;

So make sure that you are not using line break

  1. after return, break and continue statements
  2. after expression in postfix ++ and -- operators.
Write comments