CodeBlanks Logo Icon CodeBlanks

Nested loops

JavaScript course · Beginner · Lesson 40/133

Learn to traverse structures like tables and matrices with nested loops.

Nested loops

A nested loop is a loop inside another loop's body. Each time the outer loop runs, the inner loop runs to completion.

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

Here the outer loop runs 2 times, and the inner loop runs 3 times per outer step. That's 6 prints in total. Nested loops are used to walk through two-dimensional structures like tables and matrices.

Walking a matrix

Nested loops are ideal for walking two-dimensional structures made of rows and columns. The outer loop walks rows, the inner loop walks columns.

for (let row = 1; row <= 2; row++) {
  for (let col = 1; col <= 3; col++) {
    console.log(row + "," + col);
  }
}

Here three columns are walked for each row. Output: 1,1, 1,2, 1,3, 2,1, 2,2, 2,3. This way a grid can be scanned cell by cell.

Exercise Print a triangle pattern

Use nested for loops to print a 3-row star triangle. Each row has as many stars as its row number. Build each row in a row variable and print it with console.log(row). Expected output:

*
**
***
Show example solution
for (let i = 1; i <= 3; i++) {
  let row = "";
  for (let j = 1; j <= i; j++) {
    row += "*";
  }
  console.log(row);
}

Exercise A 3x3 multiplication grid

Use nested for loops to print a 3x3 multiplication grid. The outer loop walks i, the inner loop walks j, both from 1 to 3. In each cell add i * j to a row variable separated by a space, and print each row with console.log(row).

Show example solution
for (let i = 1; i <= 3; i++) {
  let row = "";
  for (let j = 1; j <= 3; j++) {
    row += (i * j) + " ";
  }
  console.log(row);
}

Test yourself

  1. What does this code print?

    let sum = 0;
    for (let i = 1; i <= 5; i++) {
      for (let j = 1; j <= 5; j++) {
        sum++;
      }
    }
    console.log(sum);
    • 5
    • 10
    • 15
    • 25
    Show answer

    25 — The inner loop runs 5 times per outer step. 5 outer × 5 inner = 25 increments.

  2. Complete the inner loop lower bound

    for (let i = 3; i >= 1; i--) {
      for (let j = 3; j >= ____; j--) {
        console.log(i * j);
      }
    }
    Show answer
    for (let i = 3; i >= 1; i--) {
      for (let j = 3; j >= 1; j--) {
        console.log(i * j);
      }
    }
  3. Match outer and inner loop roles

    outer loop
    iterates rows
    inner loop
    iterates columns
    i * j
    cell value

All lessons in Beginner