Loops: Repeating Work
Repeat code with for, while and for...of loops, build results with the accumulator pattern, and avoid off-by-one errors and infinite loops.
Welcome back!
Step 1 of 14Learn
Doing it 1,000 times without typing it 1,000 times
A teacher wants to print a certificate line for each of 30 students. A shop wants to add up 200 order totals. A game checks every enemy, 60 times a second. Writing the same line over and over is not an option. Loops repeat a block of code.
The classic for loop has three parts in its parentheses:
for (let i = 1; i <= 5; i++) {
console.log(`Lap ${i}`);
}
// Lap 1, Lap 2, Lap 3, Lap 4, Lap 5- Initialization
let i = 1runs once at the start. - Condition
i <= 5is checked before every pass; when it is false, the loop ends. - Update
i++runs after every pass.
Each pass is an iteration. The variable i is the loop counter, by tradition named i.
The most common loop bug is the off-by-one error: looping one time too many or too few. i < 5 starting from 0 runs five times (0 to 4), and so does i <= 5 starting from 1. But i <= 5 starting from 0 runs six times. When you write a loop, trace the first and last values of the counter on purpose.
Step 2 of 14Diagram
Inside a for loop
Before the cycle starts, let i = 1 runs exactly once. Then the loop goes round until the condition is false.
Tap a shape with to see more.
- Check i <= 5
False? The loop ends and code after it runs.
- Run the body
console.log(
Lap ${i})- Update: i++
Runs after every pass, then back to the check.
Step 3 of 14Practice · Work it out
How many times does this loop print?
``js
for (let i = 0; i <= 10; i += 2) {
console.log(i);
}
``
Step 4 of 14Learn
The accumulator pattern
Most loops do the same thing: start with an empty result and build it up one item at a time. This is the accumulator pattern:
let sum = 0; // 1. start value
for (let i = 1; i <= 100; i++) {
sum += i; // 2. update each time
}
console.log(sum); // 3. use the result: 5050The start value depends on the operation:
- Adding up: start at 0.
- Multiplying (like a factorial): start at 1; starting at 0 makes every product 0.
- Building a string: start with "".
- Collecting items: start with an empty array [].
- Finding a maximum: start with the first item, or
-Infinity.
let stars = "";
for (let i = 0; i < 5; i++) {
stars += "*";
}
console.log(stars); // "*****"A frequent mistake is declaring the accumulator inside the loop. Then it resets to 0 on every pass and the final result is just the last item. Declare it before the loop, update it inside, use it after.
Step 5 of 14Practice · Code challenge
Write a function factorial(n) that returns n! = 1 × 2 × … × n using a loop. By definition, factorial(0) is 1.
factorial(5)factorial(1)factorial(0)factorial(10)
Step 6 of 14Learn
while loops, for...of and break
A while loop repeats as long as a condition is true. Use it when you don't know in advance how many iterations you need:
let balance = 1000;
let years = 0;
while (balance < 2000) {
balance *= 1.07; // 7% growth per year
years++;
}
console.log(years); // 11Something inside a while loop must eventually make the condition false. If not, you get an infinite loop, and the browser tab freezes. Forgetting years++ or the balance update would do exactly that.
The for...of loop walks through each item in an array or each character of a string, without a counter:
const fruits = ["apple", "kiwi", "mango"];
for (const fruit of fruits) {
console.log(fruit.toUpperCase());
}Prefer for...of when you need each item but not its position; it removes the chance of an off-by-one error.
Two keywords control loops from inside: break exits the loop immediately (useful once you've found what you were searching for), and continue skips the rest of the current iteration and moves to the next.
Step 7 of 14Practice · Chart
The while loop from above: balance growing 7% a year
The loop runs while balance < 2000. Tap the year when it stops.
Tap the point that answers the question, then press Check.
| years | balance |
|---|---|
| 0 | $1,000 |
| 1 | $1,070 |
| 2 | $1,145 |
| 3 | $1,225 |
| 4 | $1,311 |
| 5 | $1,403 |
| 6 | $1,501 |
| 7 | $1,606 |
| 8 | $1,718 |
| 9 | $1,838 |
| 10 | $1,967 |
| 11 | $2,105 |
Step 8 of 14Note
Step 9 of 14Practice · Put in order
Put these parts of a for loop in the order they happen during the first iteration.
Drag the items, or use the arrow buttons, to put them in order.
- Check the condition (i < 3)
- Run the initialization (let i = 0)
- Run the loop body
- Run the update (i++)
- Check the condition again
Step 10 of 14Note
Step 11 of 14Practice · Spot the mistake
This function should return the sum of the numbers in an array, but it always returns only the last number. Which line causes the bug?
Step 12 of 14Note
Step 13 of 14Compare
Which loop when?
| Aspect | for | for...of | while |
|---|---|---|---|
| Best for | Counting with a number | Every item of an array or string | Unknown number of repeats |
| Gives you | The counter i | Each item directly | Whatever your condition checks |
| Main risk | Off-by-one bounds | None: cannot overrun | Infinite loop if nothing changes |
| Example | for (let i = 0; i < 10; i++) | for (const s of songs) | while (balance < 2000) |
Step 14 of 14Practice · Code challenge
Write a function countVowels(text) that returns how many vowels (a, e, i, o, u, upper- or lowercase) are in the string.
countVowels("hello")countVowels("JavaScript")countVowels("rhythm")countVowels("AEIOU aeiou")
Lesson complete!