DEV Community

Duncan McArdle
Duncan McArdle

Posted on • Originally published at duncan-mcardle.Medium

3 2

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:

const dataSet = [
['John', 'Jack', 'Jamie'],
['Amy', 'Sarah', 'Catherine'],
['Jack', 'Sarah', 'Jack'],
];

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:

// Loop through the dataset
for (let i = 0; i < dataSet.length; i++) {
// Loop through each record's values
for (let x = 0; x < dataSet[i].length; x++) {
// Check if a "Jack" was found
if (dataSet[i][x] == 'Jack') {
console.log('Found a Jack in data set row ' + i + ', position ' + x + '!');
break;
}
}
}
console.log("The loops have finished!");

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:

// Loop through the dataset
outerLoop: for (let i = 0; i < dataSet.length; i++) {
// Loop through each record's values
for (let x = 0; x < dataSet[i].length; x++) {
// Check if a John was found
if (dataSet[i][x] == 'Jack') {
console.log('Found a Jack in data set row ' + i + ', position ' + x + '!');
break outerLoop;
}
}
}
console.log('The loops have finished!');

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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more