home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

2.4. Optional Semicolons

Simple statements in JavaScript are generally followed by semicolons (;), just as they are in C, C++, and Java. The semicolon serves to separate statements from each other. In JavaScript, however, you may omit the semicolon if each of your statements is placed on a separate line. For example, the following code could be written without semicolons:

a = 3;
b = 4;

But when formatted as follows, the first semicolon is required:

a = 3; b = 4;

Omitting semicolons is not a good programming practice; you should get in the habit of using them.

Although JavaScript theoretically allows line breaks between any two tokens, the fact that JavaScript automatically inserts semicolons for you causes some exceptions to this rule. Loosely, if you break a line of code in such a way that the line before the break appears to be a complete statement, JavaScript may think you omitted the semicolon and insert one for you, altering your meaning. Some places you should look out for this are with the return, break, and continue statements (which are described in Chapter 6). For example, consider the following:

return
true;

JavaScript assumes you meant:

return;
true;

However, you probably meant:

return true;

This is something to watch out for -- this code does not cause a syntax error and will fail in a nonobvious way. A similar problem occurs if you write:

break
outerloop;

JavaScript inserts a semicolon after the break keyword, causing a syntax error when it tries to interpret the next line. For similar reasons, the ++ and -- postfix operators (see Chapter 5) must always appear on the same line as the expressions to which they are applied.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.