JavaScript · Lesson 29 of 138
Practice: Times Tables
Nested loops.
Let's print a small times table, from one to five. Each row is one number, multiplied by one to five. That needs a loop inside a loop, called a nested loop.

- A times table
- Rows and columns
- A loop inside a loop
Rows and columns
The outer loop picks the row. For each row, the inner loop runs all the way through the columns, building up a line of text. Pad start adds spaces in front, so the numbers line up in neat columns. Run it.
app.jsjavascript
for (let row = 1; row <= 5; row++) {
let line = "";
for (let col = 1; col <= 5; col++) {
line += String(row * col).padStart(4);
}
console.log(line);
}Output
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
How many steps?
The inner loop runs five times for each of the five rows, so twenty five steps in total. Nested loops multiply. A hundred rows and a hundred columns means ten thousand steps. That's fine here, but it's worth remembering when lists get big.
| key | value |
|---|---|
| Outer loop | rows |
| Inner loop | columns |
| Steps | rows × columns |
| padStart | line up columns |
Summary
A nested loop runs the inner loop completely for each round of the outer loop. Next, a quiz on control flow.
Key takeaways- Loop inside a loop
- Rows × columns steps
- padStart to align
Next up: Control Flow Quiz — test yourself