JavaScript - Nested Loop


In JavaScript, a loop inside another loop is called a nested loop. We need nested loop when we iterate over multi-dimension array or matrix. When we have to perform repeated actions on each element of an array we do use nested array.

Nested loops in JavaScript

Let's say we have two arrays, one is an array of rows and another is an array of columns. We can use nested loop to iterate over each element of the array of rows and then iterate over each element of the array of columns.

Syntax of Nested Loop

Below is the syntax of nested loop in JavaScript.

for (let i = 0; i < rows.length; i++) {
   for (let j = 0; j < columns.length; j++) {
      // code block to be executed
   }
}

Nested Loop Using for Loop

In the following code snippet that demonstrates how we can use nested for loops.

let rows = [1, 2, 3];
let columns = [4, 5, 6];

for (let i = 0; i < rows.length; i++) {
   for (let j = 0; j < columns.length; j++) {
      console.log(rows[i] + " " + columns[j]);
   }
}

Output

1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6

We have two arrays, one is an array of rows and another is an array of columns. We are using nested loop to iterate over each element of the array of rows and then iterate over each element of the array of columns.

Nested Loop Using while Loop

We can use while loop same as for loop to iterate through the array elements. Below is the code snippet that shows how we can use nested while loops.

let rows = [1, 2, 3];
let columns = [4, 5, 6];

let i = 0;
while (i < rows.length) {
   let j = 0;
   while (j < columns.length) {
      console.log(rows[i] + " " + columns[j]);
      j++;
   }
   i++;
}

Output

1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6

We have two arrays, one is an array of rows and another is an array of columns. We are using nested loop to iterate over each element of the array of rows and then iterate over each element of the array of columns.

Advertisements