Loops That Repeat
Use for and while loops to repeat game actions, count through levels and enemies, and avoid the infinite loop that freezes your browser tab.
Welcome back!
Step 1 of 12Learn
Never copy and paste ten times
Imagine drawing a row of ten coins. Without loops, you'd write ten almost identical lines, and if you later wanted twenty coins, you'd write ten more. Programmers hate repetition, because every copy is another place for a bug to hide. A loop runs the same block of code many times.
The most common loop in games is the for loop:
for (let i = 0; i < 10; i++) {
drawCoin(i * 40, 100);
}The parentheses hold three parts, separated by semicolons:
- Start:
let i = 0creates a counter variable. - Condition:
i < 10is checked before every round. While it's true, the loop continues. - Step:
i++runs after every round, adding one to the counter.
So i takes the values 0, 1, 2 and so on up to 9: ten rounds in total. The coins land at x = 0, 40, 80, up to 360.
Why start at 0 instead of 1? Partly habit, and partly because lists in JavaScript (arrays, coming soon) also start counting at 0. With i = 0 and i < 10, the number in the condition is exactly the number of repetitions, which makes loops easy to read.
Step 2 of 12Practice · Diagram
One round of a for loop
Which part decides when the loop stops?
Tap the shape that answers the question, then press Check.
- Start: let i = 0
Runs once, before the first round.
- Check: i < 10 ?
Checked before every round. False ends the loop.
- Run the body
drawCoin(i * 40, 100);- Step: i++
Runs after every round, then back to the check.
Step 3 of 12Practice · Work it out
How many times does the body of for (let i = 0; i < 7; i++) run?
Step 4 of 12Learn
Counting in different steps
The three parts of a for loop can be changed to count however you need.
Count by a different step. To place a fence post every 50 pixels across a 400-pixel screen:
for (let x = 0; x <= 400; x += 50) {
drawPost(x);
}That's x = 0, 50, 100, up to 400: nine posts. Notice <= this time, so 400 itself is included.
Count down. A countdown before a race:
for (let n = 3; n >= 1; n--) {
console.log(n);
}
console.log("Go!");This prints 3, 2, 1, then Go!.
Add things up. Loops are perfect for totals. To add the bonus points for every level from 1 to 5, where level n is worth n times 100 points:
let total = 0;
for (let level = 1; level <= 5; level++) {
total += level * 100;
}After the loop, total is 100 + 200 + 300 + 400 + 500 = 1500. The pattern "start a total at 0, add inside the loop" appears in nearly every program you'll ever write, from adding up a shopping cart to counting enemies left on screen.
Step 5 of 12Practice · Chart
Running total of level bonuses (level n = n × 100)
After which level does the total first go above 1,000?
Tap the bar that answers the question, then press Check.
Step 6 of 12Practice · Fill in the blanks
Fill in the blanks
To count down from 10 to 1, write: for (let n = ; n >= 1; n) { ... }
Step 7 of 12Learn
While loops and the infinite loop
A while loop repeats as long as a condition stays true, without a built-in counter:
let health = 100;
while (health > 0) {
health -= 15;
hits++;
}Use while when you don't know in advance how many rounds you need: keep spawning until there are enough enemies, keep rolling until you get a six.
Both kinds of loop share one danger. If the condition never becomes false, the loop never ends. This is an infinite loop, and in a browser it freezes the tab: buttons stop responding, animations stop, and eventually the browser offers to kill the page. Forgetting health -= 15 above would do it.
Here's a twist that matters for games: you might think the game itself should be one giant while (true) loop. It shouldn't. A loop like that would hog the browser and the screen would never redraw. Instead, browser games use a special function that runs your code once per screen refresh, which you'll build in the animation lesson. Ordinary loops are for quick jobs inside a single frame, like updating every enemy.
Step 8 of 12Note
Step 9 of 12Practice · Chart
while (health > 0) { health -= 15; hits++; }
After which hit is the condition health > 0 false for the first time?
Tap the point that answers the question, then press Check.
| Item | health |
|---|---|
| Start | 100 |
| Hit 1 | 85 |
| Hit 2 | 70 |
| Hit 3 | 55 |
| Hit 4 | 40 |
| Hit 5 | 25 |
| Hit 6 | 10 |
| Hit 7 | -5 |
Step 10 of 12Practice · Spot the mistake
One of these loops never stops. Which line starts the infinite loop?
Step 11 of 12Practice · Code challenge
Write levelBonus(maxLevel) that adds up the bonus for every level from 1 to maxLevel, where level n is worth n × 100 points. For example, levelBonus(3) is 100 + 200 + 300 = 600.
levelBonus(3)levelBonus(5)levelBonus(1)levelBonus(0)
Step 12 of 12Practice · Choose one
What does this code print? let n = 1; while (n < 20) { n = n * 2; } console.log(n);
Lesson complete!