JavaScript: The Definitive Guide

Previous Chapter 5

5.5 for

The for statement is a loop that is often more convenient than the while statement. The for statement takes advantage of a pattern common to most loops (including the while loop example above). Most loops have a counter variable of some kind. This variable is initialized before the loop starts. Then it is tested as part of the expression evaluated before each iteration of the loop. Finally, the counter variable is incremented or otherwise updated at the end of the loop body just before the expression is evaluated again.

The initialization, the test, and the update are the three crucial manipulations of a loop variable, and the for statement combines these three and makes them an explicit part of the loop syntax. This makes it especially easy to understand what a for loop is doing, and prevents mistakes such as forgetting to initialize or increment the loop variable. The syntax of the for statement is:

for(initialize ; test ; increment)

The simplest way to explain what this for loop does is to show the equivalent while loop:[1]

[1] As we'll see when we consider the continue statement, this while loop is not an exact equivalent to the for loop.

while(test) {

That is, the initialize expression is evaluated once, before the loop begins. To be useful, this is an expression with side effects, usually an assignment. The test expression is performed before each iteration and controls whether the body of the loop is executed. If the test expression is true, then the statement that is the body of the loop is executed. Finally, the increment expression is evaluated. Again, this must be an expression with side effects in order to be useful. Generally it will be an assignment expression or will use the ++ or -- operators.

The example while loop of the previous section can be rewritten as the following for loop, which counts from 0 to 9:

    document.write(count + "<br>");

Notice how this syntax places all the important information about the loop variable on a single line, which makes it very clear how the loop will execute. Also note that placing the increment expression in the for statement itself simplifies the body of the loop to a single statement, and we don't even need to use curly braces to produce a statement block.

Loops can become a lot more complex than these simple examples, of course, and sometimes there will be more than one variable changing with each iteration of the loop. This is the only place that the comma operator is commonly used in JavaScript--it provides a way to combine multiple initialization and increment expressions into a single expression suitable for use in a for loop. For example:

for(i = 0, j = 10 ; i < 10 ; i++, j--)
    sum += i * j;

Previous Home Next
while Book Index

Hosted by uCoz