How to stop a loop from inside a nested loop
JavaScript, Web Design
There are times in JavaScript when we’ll have a loop inside of another loop and we’ll want to stop the outer most loop from inside the inner one. Here is a block of code that is showing what I’m talking about:
var i = 0;
while(i < 3){
for(x=1; x<=10;x++){
if(x%5 == 0){
//we want to to stop the while loop here
}
document.write(x);
}
i++;
}
We have a for loop that is inside of a while loop and we want to be able to stop the while loop from inside the for loop. This code prints out all the numbers that aren’t divisible by five. When we come across a number that is divisible by 5, we want the outer loop (the while loop) to stop, not the inner for loop. So this how we do that (emphasis added to additions):
var i = 0;
outerLoop: while(i < 3){
for(x=1; x<=10;x++){
if(x%5 == 0){
break outerLoop;
}
document.write(x);
}
i++;
}
All we do is add a label to the while loop called outerLoop with a colon : Then when we want the outer loop, not the inner loop, to stop we can use the label we created to do so with the “break outerLoop” statement found in the for loop. This can give you the ability to stop the main parent loop from within the inner child loop which can be useful. Hope that tip helped out. If you’d like to learn more be sure to check out our JavaScript training. Have an amazing day!