In JavaScript, there are times when we need to break out of nested loops. Using break only exits the innermost loop. However, we can employ several techniques to achieve our goal.
overview
In JavaScript, there are three ways to exit loops:
- Break Statement: The
break
statement immediately exits the innermost loop or a switch statement.
|
|
- Continue Statement: The
continue
statement is similar to break, but instead of exiting a loop, it starts a new iteration of the loop.
|
|
- Return Statement: The
return
statement specifies the value returned from a function and can only appear inside a function body.
|
|
Exiting Nested Loops
- Using Labels
JavaScript allows us to label loop statements and use the break statement to exit a specified loop level.
|
|
In this example, once a condition is met, break outerLoop will immediately exit all loops. The continue outerLoop
can achieve a similar effect.
- Using Functions and Return
Another method is to encapsulate the loops within a function and use return
to terminate the function’s execution, thereby exiting the loops.
|
|
Here, the return
statement directly terminates the entire function.
- Using Try/Catch/Throw
This method utilizes JavaScriptâs exception handling mechanism. Inside the loop, when a condition is met, we can throw an exception and catch it in an outer try/catch
statement to exit the loop.
|
|
In this case, when i * j
exceeds 10, we throw a string as an exception and catch it in the outer try/catch
.
This method can also be used to exit a forEach
loop:
|
|
In this example, we iterate over an array using forEach
. When an element exceeds 2, we throw an exception, which is then caught and printed.
By using these techniques, you can effectively manage your nested loops in JavaScript.