while Loops
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Repeat While Something is True
A `for` loop is perfect when you know how many turns you need. But sometimes you only know when to stop: attack until the opponent is KO, train until the level is high enough... That's the job of `while`.
let wildHP = 50;
while (wildHP > 0) {
console.log("Zap attacks! Wild HP: " + wildHP);
wildHP -= 20;
}
console.log("The wild Codémon is KO!");The loop checks `wildHP > 0` before each turn. As long as it is `true`, the block runs. As soon as it is `false`, JavaScript jumps to the code after the loop.
Exercise 2 — Anatomy of a while Loop
`while` is simpler than `for`: only a condition, no built-in counter.
while (condition) {
// code repeated while the condition is true
}That means you are responsible for changing something inside the block, so the condition eventually becomes `false`. Compare these two versions of the same countdown:
for (let i = 3; i > 0; i--) {
console.log(i);
}let i = 3;
while (i > 0) {
console.log(i);
i--;
}The initialization goes before the loop, the update goes inside the block. Same result, same three ingredients, just placed differently.
The Infinite Loop
If the condition never becomes `false`, the loop never stops and your program freezes. Forgetting the `i--` above would do exactly that. Always make sure something in the block moves the condition towards `false`.
Exercise 3 — Predict the while
What will this code print?
let energy = 5;
while (energy < 20) {
energy += 5;
console.log(energy);
}10, 15, 205, 10, 155, 10, 15, 2010, 15Hint : Look at the order of the two lines inside the block: the variable changes before it is printed. Then check the condition again with the new value.
Exercise 4 — Complete the while Loop
Complete the loop so Aquachu keeps drinking potions until its HP reaches at least 100.
Hint : The block should keep running as long as the HP is still too low, and every potion should push the HP in the right direction.
Exercise 5 — When You Can't Predict the Number of Turns
The real power of `while` shows up with values you can't predict, like random numbers. Here Pyrochu trains until it reaches level 10, but the XP gained in each session is random:
let level = 1;
let sessions = 0;
while (level < 10) {
let gained = Math.floor(Math.random() * 4) + 1;
level += gained;
sessions++;
console.log("Session " + sessions + ": level " + level);
}
console.log("Goal reached in " + sessions + " sessions!");Run it several times: the number of sessions changes every time. A `for` loop couldn't do this, because you don't know the number of turns in advance.
Rule of thumb: known number of turns → `for`. Unknown number of turns but a known stop condition → `while`.
Exercise 6 — How Many Iterations?
What will this code print?
let power = 10;
let turns = 0;
while (power < 100) {
power *= 2;
turns++;
}
console.log(turns);435160Hint : Write down the value of the variable after each turn until the condition fails. The answer is how many times the block ran, not the final value.
Exercise 7 — Catch Attempts
You throw balls at a wild Florachu. Each throw has a chance to catch it. Complete the loop so it keeps throwing as long as `caught` is `false`.
Hint : The loop must keep going as long as the catch has not happened yet. Be careful to compare, not assign.
Exercise 8 — Ingredients of a while Loop
Match each piece of a `while` loop with its role.
let i = 3; written before the loopwhile (i > 0)i-- inside the blockExercise 9 — Spot the Infinite Loop
With `hp` starting at 30, which of these loops never ends?
let hp = 30;while (hp > 0) { console.log(hp); }while (hp > 0) { hp -= 10; }while (hp < 0) { hp = 0; }for (let i = 0; i < 3; i++) { hp--; }Hint : For each loop, ask two questions: is the condition true at the start, and does anything inside the block ever change it?
Exercise 10 — Combining Conditions
The condition of a `while` can be as rich as any other condition: comparisons, `&&`, `||`... Here the battle lasts while Pyrochu is alive and at most 5 turns:
let pyrochuHP = 100;
let turn = 0;
while (pyrochuHP > 0 && turn < 5) {
turn++;
pyrochuHP -= 30;
console.log("Turn " + turn + " - Pyrochu HP: " + pyrochuHP);
}
console.log("Battle over after " + turn + " turns");The loop stopped after 4 turns because `pyrochuHP > 0` became `false` first. Try changing the damage to `10`: this time the 5-turn limit is what stops it.
Exercise 11 — Until KO
A wild Metachu with 75 HP appears! Aquachu deals 20 damage per turn. 1. Loop as long as Metachu still has HP 2. Each turn: increase `turns` by 1, reduce `metachuHP` by `damage`, then print `"Turn X: Metachu has Y HP"` 3. After the loop, print `"KO in X turns!"`
let metachuHP = 75;
let damage = 20;
let turns = 0;
// Write your loop here