Skip to content

Instantly share code, notes, and snippets.

@badsyntax
Created April 5, 2013 08:24
Show Gist options
  • Save badsyntax/5317545 to your computer and use it in GitHub Desktop.
Save badsyntax/5317545 to your computer and use it in GitHub Desktop.
Using Javascript labels to break out of a nested loop
// Break out of a nested loop when both indexes are equal to 1
// It's a stupid example, but demonstrates how to use labels
// Traditional (alternatively we could adjust the value of 'i' to break the outer loop)
var iteration1 = 0;
var found = false;
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
iteration1++;
if (i === 1 && j === 1) {
found = true;
break;
}
}
if (found) {
break;
}
}
console.log(iteration1); // 5
// Using labels
var iteration2 = 0;
top: for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
iteration2++;
if (i === 1 && j === 1) {
break top;
}
}
}
console.log(iteration2); // 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment