So is this actually naming the loop to nextLoop
? So when it says continue nextLoop
, does it go back to the top right away?
var total = 0;
nextLoop:
for ( var i = 0; i < 7; ++i ) {
for ( var j = 0; j < 6 ; ++j ) {
if ( i < 5 )
continue nextLoop;
total++;
}
total++;
}
total++;
document.write( total );
Edit:
Is that naming the loop nextLoop:
? If so, what else can you name? Any references to why naming stuff can be useful?
Yes. This is useful for when you have a loop nested inside another loop and you want to continue the outer loop. Here's a page on MDC about it. So in your case, during the i = 2
loop if, from within the j
loop, you say continue nextLoop
, it'll jump out of the j
loop, do the i
increment, and continue with i = 3
.
Using continue
with labels is not usually good practice; it can indicate that the logic needs to be refactored. But it's perfectly valid syntactically and I expect someone will chime in with an example situation where they feel it's absolutely necessary.
Edit Answering your edit, the label (name) of the loop is nextLoop
(without the colon): You can label statements and then use those labels as the targets of continue
and break
. Check out the spec for details. The typical use is to label loops as in your example and either continue
or break
them, but note that break
also applies to nested switch
statements -- you can label them like loops and break to an outer one from within one of the inner one's cases. You can even intermix them so you can break a loop from within a switch (the label namespace is common to both).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With