Label Use Case
The ideal use case for a label is typically with a nested loop or conditional.
In the above example, we can break out of the outer loop early by calling
break outer; and it will immediately stop the outer loop. Brilliant! Similarly, you can do the same thing with
switch statements, and leave those blocks early.
You can also label just a plain block of code. This is terribly out of fashion and will only work in non strict mode. More importantly, since ES6 modules are strict mode by default, using a label on a code block will cause your code to break. Generally speaking, I don’t recommend doing this.
// You can do this.
// But you really shouldn't.
console.log('this will run');
console.log('this will not');
I mentioned earlier that the label pattern typically isn’t seen in use because there are other ways of achieving the same functionality. A good example of this is to use functions to have the same outcome. This also allows the resulting code to be more testable and portable.
In the above code we’ve broken the logic for both loops out into their own functions. The
outerLoop function will call whatever callback we give it and the
innerLoop function receives the value of
x as an argument. We then call
outerLoop(innerLoop); to kick off the whole thing. Both loops can escape early by returning before the loop is completed.