Optional Semicolons
Like many programming languages, JavaScript uses the semicolon
(;
) to separate statements (see
Chapter 5) from each other. This is important to
make the meaning of your code clear: without a separator, the end of
one statement might appear to be the beginning of the next, or vice
versa. In JavaScript, you can usually omit the semicolon between two
statements if those statements are written on separate lines. (You can
also omit a semicolon at the end of a program or if the next token in
the program is a closing curly brace }
.) Many JavaScript programmers (and the
code in this book) use semicolons to explicitly mark the ends of
statements, even where they are not required. Another style is to omit semicolons
whenever possible, using them only in the few situations that require
them. Whichever style you choose, there are a few details you should
understand about optional semicolons in JavaScript.
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 (and with two exceptions described below), JavaScript treats a line break as a semicolon if the next nonspace character cannot be interpreted as a continuation of the current statement. Consider ...
Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.