Nested Loops

Loops inside loops. Process grids, matrices, and multi-dimensional data.

How Nested Loops Work

The inner loop completes all its iterations for each single iteration of the outer loop.

// Outer loop runs 3 times
for (let i = 0; i < 3; i++) {
  // Inner loop runs 3 times FOR EACH outer iteration
  for (let j = 0; j < 3; j++) {
    console.log(i, j);
  }
}
// Total: 3 Ɨ 3 = 9 pairs

šŸ• Think of it like a clock:

Outer loop (i) = hours hand → moves slowly

Inner loop (j) = minutes hand → completes full rotation for each hour

For each step of the outer loop, the inner loop runs completely from start to finish.

i=0: j=0, j=1, j=2  (inner completes)
i=1: j=0, j=1, j=2  (inner completes again)
i=2: j=0, j=1, j=2  (inner completes again)

The outer loop advances only after the inner loop finishes all its iterations.

1 / 2

Grid Visualization

Watch nested loops fill a grid cell by cell.

for (let row = 0; row < 4; row++) {
  for (let col = 0; col < 4; col++) {
    // Process cell at (row, col)
  }
}
0,0
0,1
0,2
0,3
1,0
1,1
1,2
1,3
2,0
2,1
2,2
2,3
3,0
3,1
3,2
3,3

row = 0, col = 0

Step 1 of 16

Iteration Counting

Total iterations = outer Ɨ inner.

3
4

Total iterations:

3Ɨ4=12

// 3 levels deep:
for (let i = 0; i < 3; i++) {      // 3 times
  for (let j = 0; j < 4; j++) {    // Ɨ 4 times
    // Total: 3 Ɨ 4 = 12 operations
  }
}

// With 3 nested loops:
for (let i = 0; i < 10; i++) {      // 10
  for (let j = 0; j < 10; j++) {    // Ɨ 10
    for (let k = 0; k < 10; k++) {  // Ɨ 10
      // = 1,000 total operations!
    }
  }
}

āš ļø Nested loops multiply. 3 loops of 100 = 100 Ɨ 100 Ɨ 100 = 1,000,000 operations. Be careful with deep nesting!

Common Patterns

Real-world uses of nested loops.

const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

for (let row = 0; row < matrix.length; row++) {
  for (let col = 0; col < matrix[row].length; col++) {
    console.log(matrix[row][col]);
  }
}
// 1, 2, 3, 4, 5, 6, 7, 8, 9

Performance Considerations

Nested loops can be expensive. Know when to avoid them.

LoopsComplexityn=1000
1 loopO(n)1,000
2 nestedO(n²)1,000,000
3 nestedO(n³)1,000,000,000

āœ“ When nested loops are fine:

  • Small datasets (n < 100)
  • Actual 2D data (matrices, grids, tables)
  • Comparing all pairs (when there's no better algorithm)

āœ— When to avoid:

  • Large datasets — use a Set or Map for O(n) lookups instead
  • Searching — sort first, then binary search O(n log n)
  • More than 3 levels deep — refactor into functions
// āœ— O(n²) — checking duplicates with nested loop
for (let i = 0; i < arr.length; i++) {
  for (let j = i + 1; j < arr.length; j++) {
    if (arr[i] === arr[j]) found = true;
  }
}

// āœ“ O(n) — use a Set instead
const seen = new Set();
for (const item of arr) {
  if (seen.has(item)) { found = true; break; }
  seen.add(item);
}

Frequently Asked Questions

Common questions about nested loops.