Summary - Loops
- Node.js course
- Beginner
- Lesson 47/116
- 5 min
Combine for, while and for...of to write a multiplication table.
Multiplication table
In this summary we will combine for, while and for...of to write a multiplication table. The goal is to print the products of each number from 1 to 3 with 1, 2, 3.
We use two nested for loops: the outer loop walks the first factor (1-3), the inner loop walks the second factor (1-3). On each iteration we print i * j with console.log. This exercise shows how nested loops work and how two counters are used together.
Practice 3x3 multiplication table
Write two nested for loops: outer for (let i = 1; i <= 3; i++), inner for (let j = 1; j <= 3; j++). Inside the inner loop call console.log(i * j). The output must be nine lines: 1, 2, 3, 2, 4, 6, 3, 6, 9.
Starter code
// Write the nested for loops hereSample solution
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(i * j);
}
}Expected output
1 2 3 2 4 6 3 6 9
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In a nested loop, what does the inner loop do each time the outer loop iterates?
// nested for loops- Does not run
- Iterates once
- Runs fully Correct answer
- Only the first iteration
Explanation: Each time the outer loop iterates, the inner loop runs fully.
2 Write the inner loop header
for (let i = 1; i <= 3; i++) {
____ (let j = 1; j <= 3; j++) {
console.log(i * j);
}
}
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(i * j);
}
}
Explanation: The inner loop is also built with for.
3 Match each loop to its purpose
| Term | Meaning |
|---|---|
for |
Counted loop |
while |
Conditional loop |
for...of |
Array elements |
for...in |
Object keys |