A for loop suits the case where the number of repetitions is already known. Plenty of situations do not say: reading pages until the last one, asking for input until it is valid, removing items until none are left.
That is the territory of while. It counts nothing, it checks a condition before every turn and stops the moment it turns false.
Definition
while evaluates its expression, runs the block if it is true, then starts again. The number of turns depends entirely on what the block changes.
let balance = 1000;
let months = 0;
while (balance > 0) {
balance -= 250;
months++;
}
console.log(months); // 4The condition is checked before the first turn. If it is false from the start, the block never runs at all, which is the wanted behavior most of the time: an empty list should trigger no treatment.
do...while guarantees a first turn
A variant exists where the condition is checked after the block. The body therefore runs at least once, whatever happens.
let attempt = 0;
do {
attempt++;
} while (attempt < 3);
console.log(attempt); // 3The use case is the one where the condition depends on something the first turn produces, such as an input or a reply from a remote service: there is no way to test it before obtaining it. Everywhere else, while reads better, because its condition sits at the top rather than at the bottom.
while (true) and its single way out
When the stop condition cannot be written at the top, you accept an endless loop and leave it from the inside with break. This is the classic pattern of a paged read, where the number of pages is unknown until the last one arrives.
const pages = [["a", "b"], ["c"], []];
let page = 0;
const all = [];
while (true) {
const batch = pages[page];
if (!batch || batch.length === 0) break; // the only way out
all.push(...batch);
page++;
}
console.log(all); // [ 'a', 'b', 'c' ]The risk is real: if no execution path ever meets the break, the loop runs forever. The reflex to build is checking, before running anything, that every branch leads somewhere, and adding a safety counter whenever the condition depends on an outside service.
Frequently asked questions
When is while preferable to for?
When the number of turns is unknown at the moment the loop is written. A for loop announces its starting point, its end point and its step right away; if those three pieces of information do not exist, forcing it into that mold produces a loop with two of the three expressions empty. while then says the same thing more honestly.
How do you avoid an infinite loop?
By checking that at least one variable of the condition changes on every turn, along every possible path. The most frequent trap comes from a continue placed before the increment: the turn restarts without the counter having moved, and the condition stays true forever.
Does a while loop freeze the page?
Yes, for as long as it runs. JavaScript does one thing at a time in a tab: a long loop freezes rendering, clicks and animations until its last iteration. To wait for an outside event you need a Promise and await, never a busy waiting loop.