Explain Codes LogoExplain Codes Logo

How to break nested loops in JavaScript?

javascript
loop-labels
break-statement
nested-loops
Anton ShumikhinbyAnton Shumikhin·Feb 15, 2025
TLDR

To exit nested loops in JavaScript, use a label to prefix the outer loop. Then, apply break with the label to terminate both loops at once.

loopLabel: for (let i = 0; i < 10; i++) { // loopLabel is our "exit door" for (let j = 0; j < 10; j++) { if (condition) break loopLabel; // "I've got to get out of here!" 🔨💥 } }

In this code, satisfying the condition triggers an escape from loopLabel, ensuring that no time-consuming, additional iterations occur.

Loop labels explained

Right off the bat, let's get a grip on what ASPCA—ehm, loop labels—really are. A labelName acts as a detour sign on the highway of your code. When you break labelName;, JavaScript jams the brakes and bails out on the entire loop linked up with labelName.

bailout: for (let out = 0; out < 3; out++) { for (let in = 0; in < 3; in++) { if (in === 1 && out === 1) { break bailout; // goodbye, loops 👋 } } }

When to call loop labels

Crunching nested data

If you're dealing with multiple layers of loops, like an inception of loops—wait, no dreams, just loops! Labels provide a quick and clean way of managing nested structures.

Tackling complex logic

In cases where loops shoulder complicated conditions or your logic has more twists and turns than a Hollywood thriller, labels can simplify intentions and keep the script—ehm, the code—for others to follow.

Loop labels shine especially when you're cherry-picking elements in multi-dimensional arrays like a pro treasure hunter.

Boosting performance

By axing unnecessary iterations, using break with labels is like decluttering your JS engine's itinerary, enhancing efficiency.

Loop label alternatives

Are loop labels too mainstream? Let's look at other bands—ehm, ways to achieve the same:

Using a flag variable

You can hoist up a flag variable to signal the need to break nested loops. This approach is friendlier to folks who are label-phobic.

let found = false for (let i = 0; i < array.length && !found; i++) { for (let j = 0; j < array[i].length; j++) { if (array[i][j] === target) { found = true; break; // this is only an intermission, not the end! } } }

The exception - literally

You can also forcefully throw an exception causing exit from the loop. But beware! Using exceptions for regular control flow might be a bit like using an elevator for stair practice.

try { for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { if (condition) throw 'breakLoop'; // eject button pressed! 🚀 } } } catch(e) { if (e !== 'breakLoop') throw e; // rethrow if it's not "breakLoop" but "breakWindow" or anything else }

Common pitfals and best practices

Syntax is key

Ensure to choose identifier-friendly names for labels. They are identifiers, not numbers, unless you've invented numeral-labels and forgot to tell us.

Label positioning

Need your label to be a reference for the correct loop? Place it right, or it could play hide and seek in a deeply nested structure, leading to bugs who bit off more than they could 'debug'.

Time to refactor

Consider refactoring if you're skydiving into loops covered with break labels. Functions, early returns, and judicious loop-modifying conditions might offer a cleaner landing zone.