Basic · 7 of 12 · 13 min read
while
The loop for when you do not know how many iterations there are, and how to keep it from running forever.
- Control flow
while checks a condition, runs the body, and checks again. That is all of it. The reason it exists
alongside for is that sometimes you do not know how many iterations there will be until you are
inside the loop.
The shape
do...while page — same pieces, swapped order.let n = 3;
while (n > 0) {
console.log(n); // 3 / 2 / 1
n -= 1; // the body is what moves the condition
}
console.log(n); // 0
The condition is evaluated before each iteration, so a body can run zero times:
let i = 10;
while (i < 5) {
console.log('never runs');
}
console.log('done'); // straight to here
That is the difference from do...while, which checks afterwards and therefore always runs at least
once.
When while is the right choice
Draining a queue
You do not know how many items there will be, and the body can add more:
const queue = [1, 2, 3];
while (queue.length > 0) {
const item = queue.shift();
console.log('handling', item);
if (item === 2) queue.push(99); // the body changed the amount of work left
}
// handling 1 / handling 2 / handling 3 / handling 99
A for loop with a cached length would have missed the 99.
Walking a structure of unknown depth
const parent = { value: 'root' };
const child = Object.create(parent);
let node = child;
while (node !== null) {
console.log(Object.hasOwn(node, 'value') ? node.value : '(no own value)');
node = Object.getPrototypeOf(node);
}
// (no own value) / root / (no own value) ← up to Object.prototype, then null
Retrying until something succeeds
async function withRetries(fn, max = 3) {
let attempt = 0;
while (attempt < max) {
attempt += 1;
try {
return await fn();
} catch (error) {
if (attempt === max) throw error;
console.log(`attempt ${attempt} failed, retrying`);
}
}
}
Consuming pages until there are none left
async function fetchAll(firstUrl) {
const all = [];
let next = firstUrl;
while (next) {
const page = await fetch(next).then((r) => r.json());
all.push(...page.items);
next = page.nextUrl; // the response decides whether to loop again
}
return all;
}
Keeping it finite
An infinite loop in while is almost always one of three things.
The update is missing.
let n = 3;
// while (n > 0) console.log(n); // forever: n never changes
while (n > 0) {
console.log(n);
n -= 1; // ← the line that was forgotten
}
The update is unreachable, because a continue jumps over it:
let i = 0;
while (i < 5) {
if (i === 2) {
// continue; // forever: i never increments past 2
}
i += 1;
}
console.log(i); // 5
This is the one real trap while has that for does not: in a for loop the update clause runs even
after continue, because it belongs to the loop header rather than the body.
for (let i = 0; i < 5; i++) {
if (i === 2) continue; // safe — i++ still runs
}
The condition can never be false. A guard counter turns a hang into an error you can read:
let guard = 0;
let node = { parent: null };
while (node) {
if (++guard > 1000) throw new Error('cycle detected while walking parents');
node = node.parent;
}
console.log(guard); // 1
while (true) with a break
Sometimes the exit condition is only knowable in the middle of the body. Writing it as
while (true) and breaking is clearer than contorting the condition:
const lines = ['a', 'b', 'STOP', 'c'];
let i = 0;
while (true) {
const line = lines[i++];
if (line === undefined) break; // ran out
if (line === 'STOP') break; // found the terminator
console.log(line); // a / b
}
Keep the break conditions at the top of the body where a reader can find them. A while (true)
whose exit is buried forty lines down is how a hang gets shipped.
while against the alternatives
| Condition checked | Body runs at least once | Reach for it when | |
|---|---|---|---|
while |
before | no | the body decides when to stop |
do...while |
after | yes | the first attempt is unconditional |
for |
before | no | you are counting a known range |
for...of |
n/a | no | you are walking something iterable |
const empty = [];
let runs = 0;
while (empty.length) runs += 1;
console.log(runs); // 0
do { runs += 1; } while (empty.length);
console.log(runs); // 1 — do...while always does one pass
Common mistakes
Caching the length and then changing it
Mistake. const n = queue.length; while (i < n) … while the body pushes to queue.
Why it fails. The condition is frozen against a number taken before the work started.
What to do instead. Read the live value in the condition: while (queue.length > 0).
continue before the increment
Mistake. A while loop whose i += 1 sits after a continue.
Why it fails. The jump skips the increment, so the condition never advances and the loop hangs.
What to do instead. Increment at the top of the body, or use a for loop, where the update clause
runs regardless.
Using while for a known range
Mistake. let i = 0; while (i < items.length) { … i++; }.
Why it fails. Nothing breaks, but the counter, the condition and the update are now three
separate lines that can drift apart — which is exactly what a for header exists to prevent.
What to do instead. for (const item of items), or a classic for when you genuinely need the
index.
Check yourself
One question from the bank on what you just read. Answering here does not affect your quiz history.
What does continue do inside a loop?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.