Expression Statements
Compound Statements
if
else if
switch
while
do/while
for
for/in
Labels
break
continue
var
function
return
throw
try/catch/finally
with
The Empty Statement
Summary of JavaScript Statements
As we saw in the last chapter, expressions are JavaScript phrases that can be evaluated to yield a value. Operators within an expression may have side effects, but in general, expressions don't do anything. To make something happen, you use a JavaScript statement, which is akin to a complete sentence or command. This chapter describes the various statements in JavaScript and explains their syntax. A JavaScript program is simply a collection of statements, so once you are familiar with the statements of JavaScript, you can begin writing JavaScript programs.
Before we examine JavaScript statements, recall from Section 2.4, that statements in JavaScript are separated from each other with semicolons. If you place each statement on a separate line, however, JavaScript allows you to leave out the semicolons. Nevertheless, it is a good idea to get in the habit of using semicolons everywhere.
The simplest kinds of statements in JavaScript are expressions that have side effects. We've seen this sort of statement in Chapter 5. Assignment statements are one major category of expression statements. For example:
s = "Hello " + name; i *= 3;
The increment and decrement operators, ++ and --, are related to assignment statements. These have the side effect of changing a variable value, just as if an assignment had been performed:
counter++;
The delete operator has the important side effect of deleting an object property. Thus, it is almost always used as a statement, rather than as part of a larger expression:
delete o.x;
Function calls are another major category of expression statements. For example:
alert("Welcome, " + name); window.close( );
These client-side function calls are expressions, but they also affect the web browser, so they are statements, too. If a function does not have any side effects, there is no sense in calling it, unless it is part of an assignment statement. For example, you wouldn't just compute a cosine and discard the result:
Math.cos(x);
Instead, you'd compute the value and assign it to a variable for future use:
cx = Math.cos(x);
Again, please note that each line of code in each of these examples is terminated with a semicolon.
Copyright © 2003 O'Reilly & Associates. All rights reserved.