JavaScript supports a compact set of statements that you can use to incorporate a great deal of interactivity in Web pages. This chapter provides an overview of these statements.
Any expression is also a statement. See Expressions and Operators for complete information about statements.
Use the semicolon (;
) character to separate statements in JavaScript code.
See the JavaScript Reference for details about the statements in this chapter.
A block statement is used to group statements. The block is delimited by a pair of curly brackets:
{ statement_1; statement_2; . . . statement_n; }
Example
Block statements are commonly used with control flow statements (e.g. if
, for
, while
).
while (x < 10) { x++; }
Here, { x++; }
is the block statement.
Important: JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java. For example:
var x = 1; { var x = 2; }
This outputs 2 because the var x
statement within the block is in the same scope as the var x
statement before the block. In C or Java, the equivalent code would have outputted 1.
A conditional statement is a set of commands that executes if a specified condition is true. JavaScript supports two conditional statements: if...else
and switch
.
Use the if
statement to execute a statement if a logical condition is true. Use the optional else
clause to execute a statement if the condition is false. An if
statement looks as follows:
if (condition) statement_1 [else statement_2]
condition
can be any expression that evaluates to true or false. If condition
evaluates to true, statement_1
is executed; otherwise, statement_2
is executed. statement_1
and statement_2
can be any statement, including further nested if
statements.
You may also compound the statements using else if
to have multiple conditions tested in sequence, as follows:
if (condition) statement_1 [else if (condition_2) statement_2] ... [else if (condition_n_1) statement_n_1] [else statement_n]
To execute multiple statements, use a block statement ({ ... }
) to group those statements. In general, it is a good practice to always use block statements, especially in code involving nested if
statements:
if (condition) { statements_1 } else { statements_2 }
It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:
if (x = y) { /* do the right thing */ }
If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:
if ((x = y)) { /* do the right thing */ }
The following values will evaluate to false:
false
undefined
null
0
NaN
""
)All other values, including all objects evaluate to true when passes to a conditional statement.
Do not confuse the primitive boolean values true
and false
with the true and false values of the Boolean object. For example:
var b = new Boolean(false); if (b) // this condition evaluates to true
A switch
statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. A switch
statement looks as follows:
switch (expression) { case label_1: statements_1 [break;] case label_2: statements_2 [break;] ... default: statements_def [break;] }
The program first looks for a case
clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements. If no matching label is found, the program looks for the optional default
clause, and if found, transfers control to that clause, executing the associated statements. If no default
clause is found, the program continues execution at the statement following the end of switch
. By convention, the default
clause is the last clause, but it does not need to be so.
The optional break
statement associated with each case
clause ensures that the program breaks out of switch
once the matched statement is executed and continues execution at the statement following switch. If break
is omitted, the program continues execution at the next statement in the switch
statement.
A loop is a set of commands that executes repeatedly until a specified condition is met. JavaScript supports the for
, do while
, and while
loop statements, as well as label (label is not itself a looping statement, but is frequently used with these statements). In addition, you can use the break
and continue
statements within loop statements.
Another statement, for...in
, executes statements repeatedly but is used for object manipulation. See {{ linkToFragment("Object Manipulation Statements") }}.
A for
loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for
loop. A for
statement looks as follows:
for ([initialExpression]; [condition]; [incrementExpression]) statement
When a for
loop executes, the following occurs:
initialExpression
, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.condition
expression is evaluated. If the value of condition
is true, the loop statements execute. If the value of condition
is false, the for
loop terminates. If the condition
expression is omitted entirely, the condition is assumed to be true.statement
executes. To execute multiple statements, use a block statement ({ ... }
) to group those statements.incrementExpression
, if there is one, executes, and control returns to step 2.The do...while
statement repeats until a specified condition evaluates to false. A do...while
statement looks as follows:
do statement while (condition);
statement
executes once before the condition is checked. To execute multiple statements, use a block statement ({ ... }
) to group those statements. If condition
is true, the statement executes again. At the end of every execution, the condition is checked. When the condition is false, execution stops and control passes to the statement following do...while
.
Example
In the following example, the do
loop iterates at least once and reiterates until i is no longer less than 5.
do { i += 1; } while (i < 5);
A while
statement executes its statements as long as a specified condition evaluates to true. A while
statement looks as follows:
while (condition) statement
If the condition becomes false, statement
within the loop stops executing and control passes to the statement following the loop.
The condition test occurs before statement
in the loop are executed. If the condition returns true, statement
is executed and the condition is tested again. If the condition returns false, execution stops and control is passed to the statement following while
.
To execute multiple statements, use a block statement ({ ... }) to group those statements.
Example 1
The following while
loop iterates as long as n
is less than three:
n = 0; x = 0; while (n < 3) { n++; x += n; }
With each iteration, the loop increments n
and adds that value to x
. Therefore, x
and n
take on the following values:
n
= 1 and x
= 1n
= 2 and x
= 3n
= 3 and x
= 6After completing the third pass, the condition n < 3
is no longer true, so the loop terminates.
A label provides a statement with an identifier that lets you refer to it elsewhere in your program. For example, you can use a label to identify a loop, and then use the break
or continue
statements to indicate whether a program should interrupt the loop or continue its execution.
The syntax of the label statement looks like the following:
label : statement
The value of label
may be any JavaScript identifier that is not a reserved word. The statement
that you identify with a label may be any statement.
Example
In this example, the label markLoop
identifies a while
loop.
markLoop: while (theMark == true) { doSomething(); }
Use the break
statement to terminate a loop, switch
, or in conjunction with a label statement.
break
without a label, it terminates the innermost enclosing while
, do-while
, for
, or switch
immediately and transfers control to the following statement.break
with a label, it terminates the specified labeled statement.The syntax of the break
statement looks like this:
break;
break label;
The first form of the syntax terminates the innermost enclosing loop or switch
; the second form of the syntax terminates the specified enclosing label statement.
Example 1:
The following example iterates through the elements in an array until it finds the index of an element whose value is theValue
:
for (i = 0; i < a.length; i++) { if (a[i] == theValue) break; }
The continue
statement can be used to restart a while
, do-while
, for
, or label
statement.
continue
without a label, it terminates the current iteration of the innermost enclosing while
, do-while
or for
statement and continues execution of the loop with the next iteration. In contrast to the break
statement, continue
does not terminate the execution of the loop entirely. In a while
loop, it jumps back to the condition. In a for
loop, it jumps to the increment-expression
.continue
with a label, it applies to the looping statement identified with that label.The syntax of the continue
statement looks like the following:
continue
continue
label
Example 1
The following example shows a while
loop with a continue
statement that executes when the value of i
is three. Thus, n
takes on the values one, three, seven, and twelve.
i = 0; n = 0; while (i < 5) { i++; if (i == 3) continue; n += i; }
JavaScript uses the for...in
, for each...in
, and with
statements to manipulate objects.
The for...in
statement iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements. A for...in
statement looks as follows:
for (variable in object) { statements }
Arrays
Although it may be tempting to use this as a way to iterate over Array elements, because the for...in statement iterates over user-defined properties in addition to the array elements, if you modify the Array object, such as adding custom properties or methods, the for...in statement will return the name of your user-defined properties in addition to the numeric indexes. Thus it is better to use a traditional for loop with a numeric index when iterating over arrays.
for each...in
is a loop statement introduced in JavaScript 1.6. It is similar to for...in
, but iterates over the values of object's properties, not their names.
Comments are author notations that explain what a script does. Comments are ignored by the interpreter. JavaScript supports Java and C++-style comments:
Example
The following example shows two comments:
// This is a single-line comment. /* This is a multiple-line comment. It can be of any length, and you can put whatever you want here. */