Main Page

loop

Both the
break
and
continue
statements can be used in conjunction with labeled statements to return
to a particular location in the code. This is typically used when there are loops inside of loops, as in the
following example:
var iNum = 0;
outermost:
for (var i=0; i < 10; i++) {
for (var j=0; j < 10; j++) {
if (i == 5 && j == 5) {
break outermost;
}
iNum++;
}
}
alert(iNum); //outputs “55”
In this example one label,
outermost
, indicates the first
for
statement. Each loop normally executes
10 times a piece, meaning that the
iNum++
statement is normally executed 100 times and, consequently,
iNum
should be equal to 100 when the execution is complete. The
break
statement here is given one
argument, the label to break to. Doing this allows the break statement not just to break out of the inner
for
statement (using the variable
j
) but also out of the outer
for
statement (using the variable
i
).
Because of this,
iNum
ends up with a value of
55
because execution is halted when both
i
and
j
are
equal to
5
. The
continue
statement can also be used in the same way:
var iNum = 0;
outermost:
for (var i=0; i < 10; i++) {
for (var j=0; j < 10; j++) {
if (i == 5 && j == 5) {
continue outermost;
}
iNum++;
}
}
alert(iNum); //outputs “95”
In this case, the
continue
statement forces execution to continue — not in the inner loop, but in the
outer loop. Because this occurs when
j
is equal to 5, that means the inner loop misses five iterations,
leaving
iNum
equal to 95.
As you can tell, using labeled statements in conjunction with
break
and
continue
can be powerful,
but this practice can also make debugging code a problem, if it is overused. Make sure to always use
descriptive labels and try not to nest more than a handful of loops.
57
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 57


JavaScript EditorFree JavaScript Editor     Ajax Editor


©

R7