Documentation

Student-friendly HTML, CSS, and JavaScript reference with examples

Sections

Nested For-Of Loops

Nested loops are loops inside loops. Use them for arrays inside arrays (2D arrays).

Arrays of Arrays

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

Outer Loop

for (const innerArray of grid) {
  // innerArray is each sub-array
}

The outer loop goes through each sub-array.

Inner Loop

for (const innerArray of grid) {
  for (const num of innerArray) {
    // num is each number in the sub-array
  }
}

The inner loop goes through each element in the current sub-array.

Complete Example

let total = 0;
for (const subArray of [[1, 2], [3, 4]]) {
  for (const value of subArray) {
    total = total + value;
  }
}
// total is 10 (1 + 2 + 3 + 4)

How It Works

  1. Outer loop gets [1, 2]
    • Inner loop: process 1, then 2
  2. Outer loop gets [3, 4]
    • Inner loop: process 3, then 4