Main Page

The break and continue statements

Labeled statements
It is possible to label statements for later use with the following syntax:
label
:
statement
For example:
start: var iCount = 10;
In this example, the label
start
can later be referenced by using the
break
or
continue
statements.
The break and continue statements
The
break
and
continue
statements provide stricter control over the execution of code in a loop. The
break
statement exits the loop immediately, preventing any further repetition of the code while the
continue
statement exits the current repetition. It does, however, allow further repetition based on
the control expression. For example:
var iNum = 0;
for (var i=1; i < 10; i++) {
if (i % 5 == 0) {
break;
}
iNum++;
}
alert(iNum); //outputs “4”
In the previous code, the
for
loop is to iterate the variable
i
from 1 to 10. In the body of loop, an
if
statement checks to see if the value of
i
is evenly divisible by 5 (using the modulus operator). If so, the
break
statement is executed and the alert displays
“4”
, indicating the number of times the loop has
been executed before exiting. If this example is updated to use
continue
instead of
break
, a different
outcome occurs:
var iNum = 0;
for (var i=1; i < 10; i++) {
if (i % 5 == 0) {
continue;
}
iNum++;
}
alert(iNum); //outputs “8”
Here, the alert displays
“8”
, the number of times the loop has been executed. The total number of times
that the loop can possibly be executed is 9, but when
i
reaches a value of
5
, the
continue
statement is
executed, causing the loop to skip the expression
iNum++
and return to the top.
56
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 56


JavaScript EditorFree JavaScript Editor     Ajax Editor


©