Loops
The while loop
Repeat while a condition holds.
Why it exists
for is good when you know how many steps there will be: for each element of an array, from 1 to 10. But often only the stopping condition is known: divide while the number is above zero; search while the range isn't empty; retry the request until it works. while says exactly that — "while this holds, carry on".
Where it's used
- Binary search:
while (low <= high). - Greedy algorithms:
while (num >= value)— take a denomination while it fits. - Splitting a number into digits:
while (n > 0) { n = Math.floor(n / 10); }. - Reading data in chunks until it runs out.
Syntax
while (condition) {
// body: runs while the condition is true
}Examples
let n = 1;
while (n < 100) {
n *= 2;
}
n; // → 128let n = 1234;
let digits = 0;
while (n > 0) {
n = Math.floor(n / 10);
digits += 1;
}
digits; // → 4let count = 0;
while (false) {
count += 1;
}
count; // → 0let tries = 0;
do {
tries += 1;
} while (tries < 0);
tries; // → 1do...while runs at least onceResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
The condition is checked before every step. True — the body runs and the check repeats. False — the loop ends and execution moves on. If the condition is false from the start, the body never runs.
The body must bring the exit closer: change the variables the condition depends on. Otherwise the condition never becomes false — an infinite loop, and the page freezes.
do { … } while (condition) checks the condition after the step, so the body runs at least once.
break leaves the loop immediately; continue jumps to the next condition check.
Traps
How it differs from…
forloopfor puts the start, condition and step on one line — handy when the number of steps is known.
whileis for when only the condition is known.for...ofloopTo walk every element of an array, for...of is simpler and won't let you get the indexes wrong.
When to pick something else
Don't use while to walk an array by index — for...of or array methods are shorter and safer. And don't wait for events in a while (while (!loaded) {}): the loop blocks the page, so the event never arrives — use promises.