Sub topic 7
Repeating Until a Condition Changes: while and do...while
This chapter assumes you know how if statements test a condition and how truthy and falsy values behave. You should also be comfortable declaring variables with let and const and working with arrays. Both loops covered here use the same truthiness rules as if. The only difference is that they test their condition repeatedly.
A while loop is the right tool when you don't know in advance how many times the work needs to run. You keep going until something changes: a queue empties, a retry succeeds, or a number reaches a target. The counting loop, for, comes in the next chapter. It suits cases where the number of steps is known up front.
The while loop
A while loop checks its condition first. If the condition is truthy, the body runs, and then the condition is checked again. Once the condition is falsy, execution continues after the loop.
let countdown = 3;
while (countdown > 0) {
console.log(countdown);
countdown--;
}
console.log("liftoff");
// 3
// 2
// 1
// liftoffThe loop works because of three parts:
- Initialization:
countdownis set before the loop starts. - Condition:
countdown > 0is tested before every iteration. - Update:
countdown--changes the state that the condition depends on.
If the update is missing, the condition never changes and the loop never ends. Almost every infinite while loop comes from forgetting the update or writing it so that it can't make the condition false.
Conditions use truthiness
The condition does not have to be a boolean. JavaScript converts it with the same rules if uses. That allows short conditions such as while (queue.length), which stops once the length is 0, a falsy value.
const tasks = ["build", "test", "deploy"];
while (tasks.length) {
const task = tasks.shift();
console.log("running", task);
}
console.log("remaining:", tasks.length);
// running build
// running test
// running deploy
// remaining: 0Here the body updates the state itself, because shift() removes an element on every pass. The loop doesn't need a counter. The data shrinks until the condition fails.
Writing tasks.length > 0 is just as correct and states the intent more explicitly. Choose whichever style your team uses, and be consistent.
When the number of iterations is unknown
A classic example is the Collatz sequence. If n is even, halve it. If it is odd, compute 3n + 1. Repeat until n is 1. Nobody can tell you in advance how many steps that takes, so while fits naturally:
function collatzSteps(start) {
let n = start;
let steps = 0;
while (n !== 1) {
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
steps++;
}
return steps;
}
console.log(collatzSteps(6)); // 8
console.log(collatzSteps(27)); // 111The do...while loop
A do...while loop puts the condition after the body. The body therefore always runs at least once, and the condition decides whether it runs again.
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 while loop at the end prints nothing, because 10 < 3 is false on the very first check. If you changed it to a do...while, it would print once.
A good fit: retry until success
do...while is useful when you need a result before you can tell whether to keep going. Retrying an operation is a common case: you can't check whether it succeeded until you have tried at least once.
// Simulated service: fails twice, then succeeds
const responses = [null, null, "ok"];
function callService(attempt) {
return responses[attempt] ?? null;
}
const MAX_TRIES = 5;
let result;
let tries = 0;
do {
result = callService(tries);
tries++;
} while (result === null && tries < MAX_TRIES);
console.log(result, tries); // ok 3The condition combines two checks. result === null keeps the loop going while the call fails. tries < MAX_TRIES sets an upper limit, so a service that never recovers can't trap the program forever. Most retry loops in real code need a limit like this.
| Situation | Better choice | Why |
|---|---|---|
| Process items while a queue has any | `while` | The queue may already be empty |
| Retry an action until it succeeds | `do...while` | You need one attempt before you can test |
| Read input until it is valid | `do...while` | You must read input before validating it |
| Loop until a computed value hits a target | `while` | The start value may already be the target |
| Known number of steps | `for` (next chapter) | The counter, test, and update sit in one line |
Common errors
The body-scoped variable trap
Variables declared with let or const inside the do block belong to that block. The while (...) condition sits outside the braces, so it can't see them.
const lines = ["first", "second", ""];
let index = 0;
// Broken: ReferenceError: line is not defined
// do {
// const line = lines[index++];
// console.log(line);
// } while (line !== "");
// Fixed: declare the variable outside the block
let line;
do {
line = lines[index++];
if (line !== "") console.log(line);
} while (line !== "");
// first
// secondAnything the condition reads has to be declared before the do keyword.
A stray semicolon after while
let k = 0;
while (k < 3); // <- this semicolon is the whole loop body
{
k++;
}The semicolon ends the statement, so the loop body is empty, and the block in braces runs only after the loop finishes. Because k never changes inside the loop, this code hangs. Linters flag it, but it is easy to type by accident. A do...while, on the other hand, ends with while (condition);, and there the semicolon belongs. Automatic semicolon insertion usually adds it if you leave it out, but writing it explicitly is clearer.
Floating-point conditions
Testing a running decimal total for exact equality can loop forever:
// Never ends: x jumps from 0.9999999999999999 past 1
// let x = 0;
// while (x !== 1) { x += 0.1; }Changing the test to < stops the hang, but the count comes out wrong:
let x = 0;
let steps = 0;
while (x < 1) {
x += 0.1;
steps++;
}
console.log(steps); // 11, not 10After ten additions, x is 0.9999999999999999, which is still less than 1. When a loop depends on a decimal total, keep an integer counter and compute the decimal from it, or compare against a tolerance.
Intentional infinite loops
You will sometimes see while (true) with a break inside. This pattern is legitimate when the exit point falls in the middle of the body rather than at the start or end. The break statement is covered in a later chapter. Until then, try to put the exit logic in the condition, where readers expect to find it.
Summary
whiletests first and may run zero times.do...whiletests last and always runs at least once.- Both loops use truthiness, so
while (items.length)stops at0. - Every loop needs initialization, a condition, and an update that moves toward ending the loop.
- Declare any variable the
do...whilecondition reads outside the body block. - Add a maximum attempt count whenever outside state controls when the loop ends.
Exercise
What does each snippet print, and why do they differ? let a = 5; while (a < 5) { console.log(a); a++; } let b = 5; do { console.log(b); b++; } while (b < 5);
Show answer
The while version prints nothing, because 5 < 5 is false on the first check. The do...while version prints 5 once: the body runs before the condition is tested, then 6 < 5 is false and the loop stops.
Exercise
Write a function halvings(n) that uses a while loop to count how many times you must replace n with Math.floor(n / 2) until n equals 1. What does halvings(1000) return?
Show answer
function halvings(n) { let count = 0; while (n > 1) { n = Math.floor(n / 2); count++; } return count; } The sequence is 1000, 500, 250, 125, 62, 31, 15, 7, 3, 1, so halvings(1000) returns 9. Testing n > 1 instead of n !== 1 also makes the function stop immediately for inputs of 1 or less instead of looping forever on 0.
Exercise
This code throws a ReferenceError. Fix it without changing what it does. do { const guess = Math.floor(Math.random() * 10); console.log(guess); } while (guess !== 7);
Show answer
The condition can't see guess, because const scopes it to the do block. Declare it outside: let guess; do { guess = Math.floor(Math.random() * 10); console.log(guess); } while (guess !== 7);