So far, our loops have contained simple actions like printing. But what if the action we want to repeat is, itself, another loop?
This is called nested loops—a loop inside another loop.
Engagement Message
Can you imagine a situation where you'd repeat something, and within each repetition, repeat something else?
Think about organizing books on multiple shelves. For each shelf, you'd arrange every book on that shelf. That's an "outer" loop (for each shelf) containing an "inner" loop (for each book).
Engagement Message
What other everyday task might involve this "loop within a loop" pattern?
Here's how nested loops look in JavaScript:
The inner loop runs to completion before the outer loop moves to its next step.
Engagement Message
How many total lines of output will the above code have?
Great! Now let's trace through that code. When i
is 0
, the inner loop runs 3 times (for j
= 0, 1, 2). Then, i
becomes 1
, and the inner loop runs 3 times again.
The total number of console.log
calls is 2 * 3 = 6.
