You can put a loop inside another loop. This is called a nested loop. For every single iteration of the outer loop, the inner loop runs all the way through.
Think of the hands on a clock. The minute hand has to go all the way around (60 minutes) for the hour hand to move forward just once. The hour hand is the outer loop. The minute hand is the inner loop.
Here's a mini multiplication grid:
for (let row = 1; row <= 3; row++) {
let line = "";
for (let col = 1; col <= 4; col++) {
line += `${row * col}\t`;
}
console.log(line);
}
It prints
1 2 3 4 2 4 6 8 3 6 9 12
The outer loop runs 3 times (one per row). For each row, the inner loop runs 4 times (one per column), building up a line of text. Total: 3 × 4 = 12 calculations.
Drawing with loops
Nested loops are great for drawing patterns:
const height = 5;
for (let row = 1; row <= height; row++) {
let stars = "";
for (let i = 1; i <= row; i++) {
stars += "⭐";
}
console.log(stars);
}
It prints
⭐ ⭐⭐ ⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐
On row 1, the inner loop adds 1 star. On row 2, it adds 2 stars. And so on. (Could you do this one with "⭐".repeat(row) from Grade 2 instead of an inner loop? Absolutely! There's almost always more than one way to solve a problem.)
Be careful with nested loops on big numbers. A loop of 1,000 inside a loop of 1,000 runs a million times. A third loop of 1,000 inside those would run a billion times, and your computer might take a nap. If your program suddenly gets slow, look for nested loops first.