Why loops?
Imagine you have to send the same message to 100 people. Can you picture yourself
copy-pasting 100 console.log? Stop right there: loops exist for exactly
this. You tell the computer "repeat this" and it does it for you, a thousand
times if needed, never getting tired or complaining.
They are one of the most powerful tools in programming, and from here on you'll stop duplicating code for good.
The for loop
It's the most common loop when you know how many times you want to repeat. It has three parts inside parentheses, separated by semicolons:
for (initialization; condition; update) {
// code that repeats
}
for (let i = 0; i < 5; i++) {
console.log("Round number", i);
}
What happens step by step:
- Initialization (
let i = 0): runs once at the start. - Condition (
i < 5): checked before each round. If it'strue, you enter; if it'sfalse, the loop ends. - The loop body runs.
- Update (
i++): runs at the end of each round. - Go back to step 2.
By convention the counter variable is called i (for index). Starting at 0 and
using < makes the loop run exactly 5 rounds: 0, 1, 2, 3, 4.
⚠️ Classic trap: the off-by-one. Starting at
1or swapping<for<=makes the loop run one round too many or too few. Whenever something counts "almost right" but is off by one, check these two details first.
Accumulate a result
One of the patterns you'll repeat the most: a variable that lives outside the loop and grows on every round. Think of a shopping cart total that goes up with each product. Here we add up from 1 to 10:
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
}
console.log(sum); // 55 (1+2+...+10)
Examples
Count from 0 to 4
for (let i = 0; i < 5; i++) {
console.log("i =", i);
}
Add the numbers from 1 to 10
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
}
console.log("Total sum:", sum);