JavaScript Nested Loops and Iteration Counts
Quick answer
A nested loop is a loop inside another loop. For each outer iteration, the inner loop begins again and runs according to its own condition.
How it works
If both loops complete fixed independent ranges of r and c iterations, the inner body runs r × c times. When inner bounds depend on the outer index, count or sum the actual inner ranges instead. An unlabeled break inside the inner loop stops only that loop. Keep counter names distinct.
for (let row = 1; row <= 2; row++) { for (let col = 1; col <= 3; col++) { console.log(row, col); }}Expected output in Node.js:
1 11 21 32 12 22 3The inner range restarts for each row.
let pairs = 0;for (let i = 1; i <= 4; i++) { for (let j = 1; j <= i; j++) { pairs++; } }console.log(pairs);Expected output in Node.js:
10The dependent inner ranges have lengths 1, 2, 3 and 4.
Common mistakes
Not all nested loops are quadratic: bounds and early exits matter. Avoid accidentally updating the outer counter inside the inner loop.
Practice
Count ordered grid positions for a nonnegative row and column count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Nested Loops and Iteration Counts — Knowledge Check
Apply the taught concept and reason about the result.
Two loops execute 2 and 3 iterations independently. How often does the inner body run?
For inner range lengths 1, 2, 3 and 4, what is the total?
What happens to the inner loop initializer at each outer iteration?
What does unlabeled break in the inner loop leave active?
Why is it incorrect to assume all nested loops are quadratic?