Loops
Why it matters
Computers are great because they never get tired of repeating. Print a hundred lines, check a thousand numbers, go through every item in a cart — that's what loops are for: code that runs many times in a row.
The for loop
The most common loop has a counter:
for (let i = 1; i <= 5; i++) {
console.log("Step", i);
}
Output:
Step 1
Step 2
Step 3
Step 4
Step 5
The parentheses have three parts separated by ;:
let i = 1— the start: create the counter (runs once);i <= 5— the condition: the loop keeps going while it's true;i++— the step: what to do with the counter after each repetition.
One pass through the loop body is called an iteration. The counter can go backwards and with a different step:
for (let i = 10; i > 0; i -= 3) {
console.log(i);
}
Output:
10
7
4
1
Accumulating a result
A typical technique: create a variable before the loop and accumulate into it:
let total = 0;
for (let i = 1; i <= 4; i++) {
total += i * i;
}
console.log(total);
Output:
30
(1 + 4 + 9 + 16 = 30)
The while loop
while runs while the condition is true. Handy when you don't know in advance how many steps there will be:
let money = 1000;
let years = 0;
while (money < 2000) {
money *= 1.1; // +10% a year
years++;
}
console.log("Doubles in", years, "years");
Output:
Doubles in 8 years
do … while
The same, but the condition is checked after the body — so the body runs at least once:
let n = 0;
do {
console.log("Ran even though n =", n);
} while (n > 0);
Output:
Ran even though n = 0
break and continue
break— exit the loop immediately;continue— skip the rest of the current step and go to the next one.
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) continue; // skip even numbers
if (i > 7) break; // stop after 7
console.log(i);
}
Output:
1
3
5
7
Inside a function, return is often used instead of break — it exits both the loop and the function at once.
Nested loops
A loop inside a loop — for example, a multiplication table:
for (let row = 1; row <= 3; row++) {
let line = "";
for (let col = 1; col <= 3; col++) {
line += row * col + " ";
}
console.log(line);
}
Output:
1 2 3
2 4 6
3 6 9
How it works inside
The engine runs for like this: start → check the condition → body → step → check → body → step… until
the condition becomes false. If the condition never becomes false, you get an infinite loop: the
program hangs. On this site such code is stopped by a timer with an error. So always check that the
counter really moves towards the exit.
About speed: checking divisors up to √n instead of n makes a huge difference. For n = 1 000 000 007
that's about 31,623 steps instead of a billion. If a number has a divisor greater than √n, it must also
have a paired divisor smaller than √n — and we'll find that one first.
Common mistakes
- An infinite loop. Forgot
i++or changing the variable inwhile— the loop never ends. - Off by one.
i < 5gives 1…4, whilei <= 5gives 1…5. Check the boundaries on a small example. - The accumulator inside the loop.
for (…) { let sum = 0; sum += i; }— the sum is reset every time. Declare the accumulator before the loop. returninside the loop too early.return trueon the very first iteration stops the check. Return "success" only after the loop.- A semicolon after the parentheses.
for (…);{ … } — the loop has an empty body and the block runs once.
Cheat sheet
| What | How |
|---|---|
| With a counter | for (let i = 0; i < n; i++) { … } |
| While true | while (condition) { … } |
| At least once | do { … } while (condition); |
| Exit the loop | break |
| Next step | continue |
| Accumulator | let sum = 0; before the loop, sum += … inside |