JavaScript Labels
WAT? JavaScript doesn’t have labels.. Well sure it does! Well, to be fair, they’re only for controlling loop flow. Let’s take a look!
Imagine the case where we have two loops and you want to break from the inner-most loop out of the outer loop. This is often achieved with a flag:
var stop = false;
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
stop = true;
break;
}
if (stop) {
break;
}
}
With the labels, you can rewrite the above as:
outer:
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
break outer;
}
}
You can do the same with a continue inside of a nested loop. In that case, you’ll break into the next iteration of the loop you continue to:
outer:
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
continue outer;
}
console.log('this will never print');
}
Whether you think this type of mild-goto usage is a good plan (I think it is when used correctly), its good to know they’re around for when you see them in use.