# Breaking out of nested loops in Javascript

Share:

In this code snippet, we’ll find out how to break out of multiple loops in Javascript.

Suppose we have an array that contains multiple 2D arrays and we want to find out if each of those 2D arrays contains a specific number.

The way to do this is to make three nested loops. The first one to iterate through the array of 2D arrays. Then two loops each one for one of the array indexes.

Inside the third loop, there would be an if statement checking if the value at the current indexes is equal to the number we are looking for. If so we would print out the indexes.

But the loops wouldn’t stop looping upon finding the number. To make this more efficient we need to break out of the second and third loop upon finding the number. This is done by “naming”(for a lack of a better term) the loop. Then when we break out of the loop using the break keyword we specify the name of the outer most loop that we want to break out of. Like so break loop2.

To see how exactly this is done let’s take a look at the code below.

### Code:

```//For this example we will make 3 2D arrays filled with some numbers.
var TwoDArray1 = [
[3, 2, 5],
[7, 8, 9],
[8, 6, 7]
];

var TwoDArray2 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

var TwoDArray3 = [
[4, 8, 3],
[2, 5, 3],
[1, 6, 5]
];

//Here we'll maeke an array of our arrays.
var ArrayOfArrays = [
TwoDArray1,
TwoDArray2,
TwoDArray3
];

loop1:
for(var i = 0; i < 3; i++){
//First loop loops through ArrayOfArrays to get the individual 2D array.
var TwoDArray = ArrayOfArrays[i];

//Loop 2 and 3 loop through the 2D array.
loop2:
for(var j = 0; j < 3; j++){
loop3:
for(var k = 0; k < 3; k++){
//Let's say that want to find out if the 2D array contains the number 5.
//If we find it there is no need to keep looking for it, so we can just move to the next array.
if(TwoDArray[j][k] == 5){
//Print index of the number 5.
console.log("I: " +i+ ", J: " +j+ ", K: " +k);
break loop2; //This will break out of the second loop(and third as well of course).
}
}
}
}
​```

Share: