How to Break Out of Nested Loop in JavaScript Easily
In JavaScript, you can break out of nested loops by using a
label with the break statement to exit multiple loops at once. Alternatively, you can use functions with return to stop execution inside nested loops.Syntax
Use a label before the outer loop and then use break with that label inside the inner loop to exit both loops immediately.
labelName:defines a label for the loop.break labelName;exits the labeled loop.
javascript
outerLoop: for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (j === 1) { break outerLoop; } console.log(`i=${i}, j=${j}`); } }
Output
i=0, j=0
Example
This example shows how to use a label to break out of both inner and outer loops when a condition is met.
javascript
outer: for (let i = 0; i < 5; i++) { for (let j = 0; j < 5; j++) { if (i * j > 6) { break outer; } console.log(`i=${i}, j=${j}`); } } console.log('Loops ended');
Output
i=0, j=0
i=0, j=1
i=0, j=2
i=0, j=3
i=0, j=4
i=1, j=0
i=1, j=1
i=1, j=2
i=1, j=3
Loops ended
Common Pitfalls
One common mistake is trying to use break without a label, which only exits the innermost loop. Another is overusing labels, which can make code harder to read.
Using functions with return can be a cleaner alternative to labels for breaking nested loops.
javascript
for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (j === 1) { break; // Only breaks inner loop } console.log(`i=${i}, j=${j}`); } } // Correct way with label outer: for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (j === 1) { break outer; } console.log(`i=${i}, j=${j}`); } }
Output
i=0, j=0
i=1, j=0
i=2, j=0
i=0, j=0
Quick Reference
- Label + break: Use
labelName:before outer loop andbreak labelName;inside inner loop. - Function + return: Wrap loops in a function and use
returnto exit all loops. - Without label:
breakonly exits the current loop.
Key Takeaways
Use labeled break to exit multiple nested loops at once.
Without labels, break only stops the innermost loop.
Functions with return can also stop nested loops cleanly.
Avoid overusing labels to keep code readable.
Test your loops to ensure break works as expected.