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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay