Break from a nested loop in Javascript

This function uses labels for use in outer loop and inner loop so that it could be possible for us to break one or other loop, it also shows how to use break and continue in JavaScript.


function breakContinueStatements() {
var x = 0;
outerloop: //label to identify the first loop, like a goto jump
// labels are only used for nested loops
//for ever
for(;;) {
x++
innerloop: // the inner loop
for (var i = 0; i < 10; i++) {
if (x == 9) break outerloop;
if (i > 3) break;
if (x == 2) break innerloop;
if (x == 4) continue outerloop;
if ((x >= 7) && (x < 9)) continue;
console.log("x = " + x + " i = " + i);
}
}
console.log("At the end x = " + x + " i = " + i);
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s