Sub topic 7
Repeating Until a Condition Changes: while and do...while
This chapter assumes you know truthy and falsy values, comparison operators, and if statements from earlier chapters. You should also be comfortable declaring variables with let.
Use a while loop when you don't know in advance how many times the work needs to repeat. It keeps going as long as a condition stays truthy, and it stops as soon as something in the body changes the condition.
The while loop
A while loop evaluates its condition before every pass, including the first one. If the condition is truthy, the body runs. Then the condition is checked again.
let balance = 1000;
let years = 0;
while (balance < 2000) {
balance *= 1.07;
years++;
}
console.log(years); // 11
console.log(balance.toFixed(2)); // "2104.85"Nobody wrote "11" anywhere in this code. The loop found that number by repeating until the balance crossed the threshold. That is the typical job of a while loop.
The condition follows the same truthiness rules as if. In this example, the loop runs while n is non-zero and stops when it reaches 0, which is falsy:
let n = 4827;
let digits = 0;
while (n) {
n = Math.trunc(n / 10);
digits++;
}
console.log(digits); // 4The do...while loop
A do...while loop puts the condition after the body. The body therefore always runs at least once, and the loop checks the condition only after each pass.
let attempts = 0;
do {
attempts++;
console.log("attempt", attempts);
} while (attempts < 3);
// attempt 1
// attempt 2
// attempt 3
let n = 10;
while (n < 3) {
console.log("never runs");
}The second loop prints nothing because 10 < 3 is false on the very first check. This loop fits any task where you have to act once before you can decide whether to continue, such as generating a value and retrying when it is invalid:
function rollDie() {
return Math.floor(Math.random() * 6) + 1;
}
let roll;
do {
roll = rollDie();
console.log("rolled", roll);
} while (roll !== 6);Before the first roll, roll has no value worth testing, so a condition-first loop would make no sense here.
Note the semicolon after while (...) in a do...while. It is required syntax there. In a plain while, a semicolon would be a bug.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Body never changes the condition | Infinite loop; the tab or process hangs | Update the tested variable on every pass |
| Stray `;` after `while (cond)` | The empty statement loops forever, or the body runs once | Remove the semicolon |
| Using `while` when the body must run first | Duplicated setup code before the loop | Switch to `do...while` |
| Off-by-one condition (`<` vs `<=`) | One pass too many or too few | Trace the first and last pass by hand |
Choosing between them
- Use
whilewhen the condition might already be false and you may need zero passes. - Use
do...whilewhen the body has to run once before the condition means anything. - When you are counting through a known range, the
forloop in the next chapter is clearer.
Exercise
What does this code print, and why? let x = 5; do { console.log(x); x++; } while (x < 5);
Show answer
It prints 5 once. The do...while body runs before the condition is checked. After the body, x is 6, and 6 < 5 is false, so the loop stops. A plain while loop with the same condition would print nothing.
Exercise
This loop never ends: let i = 0; while (i < 3); { i++; }. Explain the bug.
Show answer
The semicolon after while (i < 3) gives the loop an empty statement as its body. That empty body runs forever because i never changes. The block { i++; } is a separate statement after the loop and is never reached. Remove the semicolon to fix it.