Labels
Level: Intermediate
Labels are an infrequently used feature of JavaScript. They allow you to name or tag different statements, usually code blocks or loops. When a block is labeled, you can use break
to break out of it by its label name. With loops, you can also use continue
to continue a loop by name.
myBlockLabel: {
console.log('Now you see me');
break myBlockLabel;
console.log('Now you dont');
}
// Logs: Now you see me
myLoopLabel: for (let i = 0; i < 3; i++) {
if (i === 1) {
continue myLoopLabel;
}
console.log('Loop: ' + i);
}
/* Logs:
Loop: 0
Loop: 2
*/
Labels are really only useful with dealing with nested blocks such as nested loops or nested switch
statements where in a nested block you might want to break out of an outer block.
let flags = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
];
outer: for (let row of flags) {
for (let flag in row) {
if (!flag) {
break outer; // exit this and outer loop
}
}
}
Normally, breaking inside the inner loop with just a break
would only break out of the inner loop allowing the outer loop to continue on to the next iteration. To break out of the outer loop too, you’d usually need another break
and some other flag to know when to use it. With labels, the inner loop can specifically target the outer loop to break out of.
More info: