Using the break Statement in Javascript
Written on 06/29/12 at 14:07:11 EST by GentleGiant
JavascriptingThere is a third way for a while loop to terminate. If the special statement break is encountered inside the while block, the loop is forced to terminate immediately. No further statements are executed and the condstmt is not retested. Execution continues with the first statement after the end of the while block. Listing 2.4 gives an example of the use of the break statement.

Listing 2.4 A while Loop with an Internal break Statement
var x = 1;
var xoddsum = 0;
var xtmp = 0;
var lastx = 0;

while ( true ) {          // 1: loop forever (well, almost)
    xtmp = xoddsum + x;     // 2: compute a trial sum
    if ( xtmp > 100 )     // 3: if it is too large, then...
         break;          // 4: we are done
    xoddsum += x;          // 5: add x to the running sum xoddsum
    x += 2;               // 6: increment x by 2
}
lastx = x;               // 7: save the final value of x in the variable lastx

The test clause of this while (statement 1) is true, which, you might well suspect, is always true. This means that there is no way for this loop to terminate unless it is forced to do so by a break statement. In statement 2 a temporary sum is formed in the variable xtmp. This sum is tested against the limit 100 in statement 3; if xtmp exceeds it then statement 4, the break statement is executed, and the loop terminates. If the test fails (xtmp is still less than 100) then the real sum is formed in statement 5. (Note that it would have been equivalent, and slightly more efficient, if we had written statement 5 as xoddsum = xtmp.) In statement 6, x is incremented by 2.

What does this while loop do? It keeps adding up numbers, odd numbers in fact, until the sum is less than 100. When the next sum would have exceeded 100, the if test succeeds, the break is executed, and the flow of control of the program reaches the first statement after the entire while block, namely statement 7. This statement saves the last value of x in a different variable, lastx. So this construction computes the largest sequence of odd numbers that can be added without having the sum exceed 100. You can easily determine for yourself that the value of lastx must be 21, since 1 + 3 + ... + 21 = 100 exactly, while 1 + 3 + ... + 21 + 23 = 123 > 100.

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