Break Out of Loop in JavaScript
- 2 minutes read
In JavaScript, the break statement can be used to break out of a loop:
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log(`Number of times this loop has run: ${i + 1}`);
}
The above loop would run ten times if it weren’t for the break
statement which is triggered at the start of the sixth iteration.
So instead, the number of times the loop has been run is printed only five times to the console.
A break
statement can be used in a for
loop, but not in a forEach
loop.
Another common use case for the break
statement is in switch
block cases.
Nested loop breaking
If you want to break out of a nested loop, you can do so like this:
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
if (j === 5) {
// Break out of child loop:
break;
}
}
}
The above example will break out of the nested loop when j
is 5
, returning to the parent loop.
If you want to break out of a parent loop from a nested loop, you can do so by labelling your loops and specifying a parent loop in a break
statement:
LoopA: for (let i = 0; i < 10; i++) {
LoopB: for (let j = 0; j < 10; j++) {
if (j === 5) {
// Break out of child AND parent loop:
break LoopA;
}
}
}
In the above example, the parent loop is labelled LoopA
and the child loop is labelled LoopB
.
When j
is 5
in the nested loop, both LoopA
and LoopB
are broken.
Conclusion
That’s it! Happy loop-breaking!