What is the best way to break from nested loops in JavaScript?

The best way to break from nested loops in JavaScript is to use labels. A label is an identifier followed by a colon (:) that allows you to control loop flow more precisely with break and continue statements.

Syntax

labelName:
for (let i = 0; i 

Example: Breaking from Nested Loops

<html>
    <body>
        <script>
            document.write("Entering the loop!<br />");
            
            outerloop: // This is the label name
            for (var i = 0; i < 5; i++) {
                document.write("Outerloop: " + i + "<br />");
                
                innerloop:
                for (var j = 0; j < 5; j++) {
                    if (j > 3) break; // Quit the innermost loop
                    if (i == 2) break innerloop; // Break inner loop only
                    if (i == 4) break outerloop; // Break outer loop
                    document.write("Innerloop: " + j + "<br />");
                }
            }
            document.write("Exiting the loop!<br />");
        </script>
    </body>
</html>
Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 2
Outerloop: 3
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 4
Exiting the loop!

Alternative Methods

While labels are the standard approach, you can also use:

  • Function return: Wrap loops in a function and use return
  • Boolean flags: Use a variable to track when to exit
  • Exception handling: Throw and catch exceptions (not recommended for control flow)

Example: Using Function Return

<html>
    <body>
        <script>
            function findValue() {
                for (let i = 0; i < 5; i++) {
                    for (let j = 0; j < 5; j++) {
                        if (i === 2 && j === 3) {
                            document.write("Found at position [" + i + ", " + j + "]");
                            return; // Exits both loops
                        }
                    }
                }
            }
            
            findValue();
        </script>
    </body>
</html>
Found at position [2, 3]

Comparison

Method Readability Performance Recommended
Labels with break Good Excellent Yes
Function return Very Good Good For complex logic
Boolean flags Fair Good Rarely

Conclusion

Labels with break statements provide the most efficient way to exit nested loops in JavaScript. For complex scenarios, consider wrapping loops in functions and using return statements.

Updated on: 2026-03-15T22:01:24+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements