JavaScript: The Definitive Guide

Previous Chapter 5
Statements
Next
 

5.8 continue

The continue statement is related to the break statement and has a syntax that is just as simple:

continue;

Like the break statement, continue can be used only within the body of a while, for, or for/in loop. Using it anywhere else will cause a syntax error.

When the continue statement is executed, the current iteration of the enclosing loop is terminated, and the next iteration begins. In a while loop, the specified expression is tested again, and if true, the loop body is executed. In a for loop, the increment expression is evaluated, then the test expression is tested again to determine if another iteration should be done. In a for/in loop, the loop starts over with the next property name being assigned to the specified variable.

The following example shows the continue statement being used to abort the current iteration of a loop when an error occurs:

for(i = 0; i < data.length; i++) {
    if (data[i] == null) 
        continue;  // can't proceed with undefined data
    total += data[i];
}

Note the difference in behavior of the continue statement for the while and for loops--a while loop returns directly to its condition, but a for loop first evaluates it increment expression, and then returns to its condition. Above, in the discussion of the for loop, we explained the behavior this loop in terms of an "equivalent" while loop. But because the continue statement behaves differently for these two loops it is never possible to perfectly simulate a for loop with a while loop.


Previous Home Next
break Book Index with

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell
This HTML Help has been published using the chm2web software.