Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Nested Loops

Nested loops place one loop inside another to handle multi-dimensional data.

They are common in grid processing, pattern printing, and pair comparisons.

Why We Need It

Some tasks require comparing every item to every other item or iterating 2D structures.

Knowing nested loops helps you handle those cases while being mindful of performance.

Syntax

for (...) {
  for (...) { ... }
}

Basic Example

1. 2D grid

const grid = [
  [1, 2],
  [3, 4],
];

for (let r = 0; r < grid.length; r++) {
  for (let c = 0; c < grid[r].length; c++) {
    console.log(grid[r][c]);
  }
}

Nested loops iterate rows and columns.

Real World Example

2. All pairs

const items = ["a", "b", "c"];

for (let i = 0; i < items.length; i++) {
  for (let j = i + 1; j < items.length; j++) {
    console.log(items[i], items[j]);
  }
}

Generate unique pairs with a nested loop.

Multiple Use Cases

Grid Iteration

Nested loops are perfect for 2D grids like tables, boards, and matrices.

The outer loop controls rows and the inner loop controls columns.

Combinations

Use nested loops to compare each item with others or generate pairs.

Be mindful of performance as the work grows quickly (O(n^2)).

Performance Awareness

Nested loops can be expensive for large datasets.

Consider breaking early with break or using smarter algorithms.

More Examples

3. Early break

let found = false;
for (let i = 0; i < 3 && !found; i++) {
  for (let j = 0; j < 3; j++) {
    if (i + j === 4) {
      found = true;
      break;
    }
  }
}
console.log(found);

Use a flag to break out of nested loops.

4. Pattern printing

let pattern = "";
for (let i = 0; i < 3; i++) {
  for (let j = 0; j <= i; j++) {
    pattern += "*";
  }
  pattern += "
";
}
console.log(pattern);

Nested loops are common in pattern generation.

Comparison

Without

for (let i = 0; i < rows; i++) {
  // no inner loop
}

With

for (let r = 0; r < rows; r++) {
  for (let c = 0; c < cols; c++) {
    // process grid cell
  }
}

Common Mistakes and Fixes

Large nested loops

Consider algorithmic alternatives for large data sets.

Forgetting break scope

Break only exits the inner loop unless you use a flag.

Unclear loop variables

Use descriptive names like row and col for readability.

Interview Questions

What is the time complexity of nested loops?

Often O(n^2), depending on bounds.

How do you break out of both loops?

Use a flag, labeled break, or return from a function.

When are nested loops necessary?

For grids, combinations, and pairwise comparisons.

Practice Problem

Practice: Use nested loops to print a 3x3 multiplication table.

// TODO: print 1..3 multiplied by 1..3

One Possible Solution

for (let i = 1; i <= 3; i++) {
  for (let j = 1; j <= 3; j++) {
    console.log(i * j);
  }
}

Frequently Asked Questions

Why are nested loops slow?

They often scale with O(n^2) or worse as data grows.

How do I break both loops?

Use a flag, labeled break, or return from a function.

When should I use nested loops?

For grids, combinations, and comparisons across pairs.

Try It Yourself

Try different grid sizes to see how nested loops behave.