Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

Nested For Loops in Javascript

A nested for loop is just a for loop inside a for loop.

Nested For Loops in Javascript

For instance consider the following Javascript code:

for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 2; j++) {
    console.log(i, j);
  }
}

The output is:

0 0
0 1
1 0
1 1
2 0
2 1

As you can see the outer loop index (variable i) goes from 0 to 2 (three times), and the inner loop index (variable j) goes from 0 to 1 (two times). Thus we get 6 lines.

This example demonstrates how to use nested for loops to iterate over a two-dimensional array.

Here is an example that uses nested for loops to sort an array of integers:

let arr = [2, 4, 8, 1, 5, 9, 3, 7, 6];

for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr.length - i - 1; j++) {
    if (arr[j] > arr[j + 1]) {
      let temp = arr[j];
      arr[j] = arr[j + 1];
      arr[j + 1] = temp;
    }
  }
}

console.log(arr); 
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

This code implements the bubble sort algorithm, which employs nested for loops to compare and swap elements in the array until it is sorted in ascending order.

At each step in the outer iteration (index “i”) we compare every element with every element to its right and if they are in the wrong order, it swaps them. To understand this algorithm, we should print the array at each step of the outer array:

let arr = [2, 4, 8, 1, 5, 9, 3, 7, 6];

document.write(arr)
document.write('<BR>')
for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr.length - i - 1; j++) {
    if (arr[j] > arr[j + 1]) {
      let temp = arr[j];
      arr[j] = arr[j + 1];
      arr[j + 1] = temp;
    }
  } 
  document.write(arr)
  document.write('<BR>')
}

The output will be:

2,4,8,1,5,9,3,7,6
2,4,1,5,8,3,7,6,9
2,1,4,5,3,7,6,8,9
1,2,4,3,5,6,7,8,9
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8,9

The first line is simply the given array. In the second line, note that the algorithm has compared 2 and 4 (and left them intact). It compared 4 and 8 (and left them intact). Then it compared 8 and 1 (and moved the 8 to the right) and in this manner moved 8 till it reached a number larger than 8 (i.e. 9).So 8 stopped there but when 9 was compared with 3, 9 began moving to the right. The end result of these maneuvers is that by the end of the second line, the largest number (i.e. 9) is at the rightmost location, i.e., where it needs to be. Similarly, by the end of the third line, the second largest number (i.e., 8) is where it needs to be), and so on. By the time all the sweeps are done we are guaranteed that every number is in its correct place.

Nested for loops in Javascript are used in many other scenarios, such as iterating through multidimensional data structures like matrices and arrays, and performing operations accordingly. Additionally, nested for loops can be employed to iterate through the properties of an object. Overall, nested for loops are useful in situations where it's necessary to perform iterative operations on multi-dimensional data structures or carry out repetitive tasks within a specific pattern.

Here is another example of using nested for loops to multiply two matrices.

const matrixA = [[1, 2, 3], [4, 5, 6]]; // 2x3 matrix
const matrixB = [[7, 8], [9, 10], [11, 12]]; // 3x2 matrix
const result = [];

for (let i = 0; i < matrixA.length; i++) {
  result[i] = [];
  for (let j = 0; j < matrixB[0].length; j++) {
    result[i][j] = 0;
    for (let k = 0; k < matrixA[i].length; k++) {
      result[i][j] += matrixA[i][k] * matrixB[k][j];
    }
  }
}

console.log(result); // Output: [[58, 64], [139, 154]]

In the above code, we initialize the result matrix as an empty array and then perform matrix multiplication using nested for loops. The outermost loop iterates over the rows of the first matrix, the second loop iterates over the columns of the second matrix, and the innermost loop calculates the dot product of the corresponding row of the first matrix and the column of the second matrix, which is then stored in the result matrix. Because the input matrices are of size 2x3 and 3x2, the final product is of size 2x2, as shown above.

If you liked learning about nested for loops, checkout our blogpost on bubblesort!

Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.