Loops inside 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:
for (let i = 1; i <= 3; i++) {
console.log("Outer loop: " + i)
for (let j = 1; j <= 4; j++) {
console.log(" Inner loop: " + j)
}
} 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!