DEV Community

Duncan McArdle
Duncan McArdle

Posted on • Originally published at duncan-mcardle.Medium

JavaScript labels (a better way to break out of nested loops)

A common problem developers will face is that of how to escape from nested loops. In this post, I’ll be using JavaScript labels to demonstrate how this can be done with a little more control.

For starters, I’ll be using this data set for the various examples, if you want to follow along:

Now, if I set you the task of finding out whether “Jack” exists in each row of the data set, you might use a crude nested loop to check all records. In addition, you’d probably add a break when you find “Jack” to prevent unnecessary checks, something like this:

And this works fine! The break; stops the inner loop, continues the outer one, and later continues code execution after the outer loop’s end, giving you an output like this:

Found a Jack in data set row 0, position 1!  
Found a Jack in data set row 2, position 0!  
The loops have finished!
Enter fullscreen mode Exit fullscreen mode

However, what if you wanted to stop both loops upon finding the first “Jack”, rather than continuing on with the code? Many developers would swap that break for a return, which will cause both loops to end. But that will also stop the code after the end of the loop from running, so we need something else.

Enter, JavaScript labels.

JavaScript Labels can be used to break and continue a specific loop, even if it isn’t the one currently being executed. The first step is to assign a label to a specific loop, and then we can reference it from within using continue or break, like so:

What this now does, is to say “Okay, I’ve got what I needed, now let’s end the outer loop”, which will in turn continue code execution after the loop is closed. The results now look more like what we wanted:

Found a Jack in data set row 0, position 1!  
The loops have finished!
Enter fullscreen mode Exit fullscreen mode

On top of the functionality provided by labels, I also feel they add a good amount of clarity to the code. If (god forbid) you have multiple nested loops, being able to label them accordingly (think schoolLoop , classLoop and studentLoop) would be a great way of keeping code understandable, without the need for additional comments at every stage.

Labels can also be used for breaking out of code blocks, but as that’s beyond the scope of this post, I’ll just leave you in the wonderful hands of Mozilla by linking to their page on JavaScript labels.

Top comments (0)