Javascript - Using the continue Statement
Written on 06/29/12 at 14:06:53 EST by GentleGiant
JavascriptingThere is another special statement that may be used inside while loops: the continue statement. The continue statement is used to force the flow of control back to the top of the while loop. When a continue statement is seen, all statements between it and the end of the while block are skipped, and execution continues at the top of the while. Listing 2.6 shows a simple use for the continue statement.

Listing 2.6 A continue Statement Returns to the Top of a while
var x = 0;
var xsum = 0;
var loopcount = 0;

while ( loopcount++ < 100 ) {          // 1: loop 100 times
    x++;                    // 2: increment x
    if ( ( x % 5 ) == 0 )          // 3: if x is divisible by 5
         continue;          // 4: skip it
    xsum += x;               // 5: otherwise, add x to xsum
}

This example adds up every number between 1 and 100 that is not divisible by 5. The numbers that are divisible by 5 are skipped by virtue of statements 3 and 4. Statement 3 computes the remainder when x is divided by 5. If that remainder is 0 then x must be evenly divisible by 5. In that case, the conditional in statement 3 is true, and statement 4 is executed. The continue statement causes execution to continue back to the top of the loop at statement 1. This means that statement 5 is not executed, so the sum always misses those values of x which are divisible by 5, and only those values.

Many programmers would write line 3 as if ( ! ( x%5 ) ). While this style is very common, it is also confusing and a potential source of error. One problem with this form is that it confuses JavaScript types by using the numerical value x%5 as if it were a logical value. This form also hides the explicit test for zero of listing 2.6. While this ! form is more compact, it is also more error prone, and should be avoided.

One striking difference between this listing and previous ones is that x is initialized to 0, not 1, and x is incremented at the top of the loop, not at the bottom. If the x++ were at the bottom, what would happen? The values 1, 2, 3, and 4 would all be gleefully added into xsum. When x reached 5, however, statement 3 would be true, the continue in statement 4 would be executed, and both xsum += x and x++ would be skipped. x would stay equal to 5 forever! Since the x++ statement is critical to the correct functioning of the loop, it must occur before the continue. If it occurs after the continue it will be skipped.

Any statement that must be executed on every pass through a loop must be placed before any continue statements.
The for Statement
The for statement is the most powerful and complex of the three flow control constructions in JavaScript. The primary purpose of the for statement is to iterate over a block of statements for some particular range of values. The for statement has the following format:

for ( initstmt; condstmt; updstmt ) {
    forblock
}

The for clause, as shown, has three parts, separated by two mandatory semicolons. The initstmt is typically used to initialize a variable, although any valid statement may be used in this position. The initstmt is always executed exactly once, when the for statement is first encountered. The condstmt is a conditional test, and serves exactly the same function as in the while statement. It is tested at the top of each loop. The for statement terminates when this condition evaluates to false. The updstmt is executed at the bottom of each loop, as if it were placed immediately after the last statement in the for block. It is typically used to update the variable that is initialized by the initstmt.

Listing 2.7 shows a simple example of a for statement. In fact, the code in this listing accomplishes exactly the same task as the code in listing 2.3. Note that this code does not bother to initialize x when it is declared. This is because the initstmt part of the for loop sets it equal to 1 immediately.

Listing 2.7 Adding Up a Sequence of Numbers Using for
var xsum = 0;
var x;

for ( x = 1; x <= 10; x++ ) {          // 1: loop while x is <= 10
    xsum += x;               // 2: add x to xsum
}

In many ways, the for statement is very much like a fancy version of the while statement. Many of the observations that were made for while also hold true for the for statement. In particular, it is possible to use the break and continue statements within a for loop. One of the advantages of a for loop is that its update statement is executed on every pass through the loop, even those passes that are cut short by a continue. The continue skips every statement in the block, but it does not cause the update statement to be skipped. The for statement may also be used unwisely, just like the while statement. If the condstmt portion of the for clause is omitted, it is as if a true conditional had been used, so that something within the for block must force looping to terminate. You will occasionally see the construction for(;;), which is identical in meaning to while ( true ). The two semicolons are mandatory.

The for statement also has some unique features that are not shared by while. The first is that variables may actually be declared and initialized within the initstmt portion. In listing 2.7 we could have dispensed with the external declaration of x, and put var x = 1; as the initialization portion of the for loop. This is often very convenient, since the loop variable (x in this case) is often used only within the loop itself, often making an external declaration pointless.

If a variable is only used inside a block of statements it should be declared at the top of that block. This clarifies your code, since it shows which sections of code use which variables (known as variable scope).
A second useful feature of the for statement is that both the initialization portion and the update portion of the for clause may contain multiple statements separated by the comma operator (,). Listing 2.8 shows another version of the code in listing 2.6, rewritten so that both x and lcnt become loop variables.

Listing 2.8 A for Loop with Multiple Initialization and Update Statements
var xsum = 0;

for ( var x = 1, lcnt = 0; lcnt < 100; x++, lcnt++ ) {
    if ( ( x % 5 ) == 0 )          // if x is divisible by 5
         continue;          // skip it
    xsum += x;               // otherwise, add x to xsum
}

This usage underlines the fact that both x and lcnt are used only within the body of the for loop. It is also much more compact than its counterpart in listing 2.6. In this example, we need not worry about the logical effect of the continue; we know that both x++ and lcnt++ will always be executed. This is also the most common and useful way to use the comma operator.

Finally, there is another form of the for statement that is used exclusively with objects and arrays in JavaScript: the for...in statement. We will see how this is used in Chapter 4, "JavaScript Objects." Figure 2.5 shows the basic structure of the for, while, and if statements, and the use of the break and continue statements within them.

See the section, "Objects, Methods and Properties in JavaScript," of Chapter 4, "JavaScript Objects," for a description of the for...in statement.

Control statements determine the flow of execution in JavaScript.

News and Comments Brought to you by: Geeks and Bloggers
The comments are owned by the poster. We aren't responsible for its content.