Lesson 35

Nested Loops

Loops inside loops

20 min
+25 XP
Step 1 of 5

What are Nested Loops?

A nested loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop!

Think of it like this:

Imagine you have 3 boxes, and each box contains 4 items. To count all items, you need to:

  • • Loop through each box (outer loop)
  • • For each box, loop through all items inside (inner loop)

Basic Nested Loop:

for (let i = 1; i <= 3; i++) {
  console.log("Outer loop: " + i)
  
  for (let j = 1; j <= 4; j++) {
    console.log(" Inner loop: " + j)
  }
}

How It Works:

When i = 1:

Inner loop runs: j = 1, 2, 3, 4

When i = 2:

Inner loop runs again: j = 1, 2, 3, 4

When i = 3:

Inner loop runs again: j = 1, 2, 3, 4

Total iterations: 3 × 4 = 12

Important:

We use different variable names for each loop (i for outer, j for inner). This helps us keep track of which loop we're in!