The for loop
Learn the for loop structure: counter, condition and increment steps.
The for loop
The for loop runs a block a fixed number of times. Its header has three parts: init, condition and increment.
for (let i = 1; i <= 3; i++) {
console.log(i);
}Here i is the counter. Each step tests the condition; if true, it runs the block and increments. When false, the loop ends.
Sum and count patterns
The for loop is commonly used for two tasks: accumulating a sum, or walking through a sequence.
Sum example:
let total = 0;
for (let i = 1; i <= 5; i++) {
total = total + i;
}
console.log(total); // 15Here total is the accumulator. Each step adds i to it. When the loop ends, total is 1+2+3+4+5 = 15.
Exercise Print 1 to 5
Use a for loop to print the numbers 1 to 5 with console.log.
Show example solution
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Exercise Sum of numbers 1 to 10
Use a for loop to compute the sum of numbers 1 to 10. Accumulate it in a total variable and finally print it with console.log(total).
Show example solution
let total = 0;
for (let i = 1; i <= 10; i++) {
total += i;
}
console.log(total);
Test yourself
-
How many times does this loop run?
for (let i = 0; i < 3; i++) { console.log(i); }- 2 times
- 3 times
- 4 times
- Forever
Show answer
3 times — i starts at 0 and runs while less than 3. It runs for 0, 1, 2 — three times.
-
Complete the loop that counts down from 5 to 1
for (let i = 5; i >= ____; i--) { console.log(i); }Show answer
for (let i = 5; i >= 1; i--) { console.log(i); } -
Match the for loop parts
- let i = 0
- init
- i < 5
- condition
- i++
- increment
- console.log(i)
- body