Basic · 8 of 12 · 11 min read
do...while
The one loop that always runs at least once, where that is exactly what you want, and the snippet interviewers use to test it.
- Control flow
do...while is while with the condition moved to the bottom. That single change means the body
always runs at least once, however false the condition is.
The shape, and the test
Note the semicolon after the while (…) — it is a statement, and it ends there.
let n = 3;
do {
console.log(n); // 3 / 2 / 1
n -= 1;
} while (n > 0);
Now the snippet that gets asked. The condition is false before the loop even begins:
let i = 10;
do {
console.log(i); // 10 ← runs once
i++;
} while (i < 5);
console.log('after', i); // after 11
Side by side with while, so the difference is unmistakable:
let a = 10;
while (a < 5) {
console.log('while', a); // never logs
a++;
}
let b = 10;
do {
console.log('do', b); // "do 10"
b++;
} while (b < 5);
| Condition checked | Minimum iterations | |
|---|---|---|
while (c) {} |
before the body | 0 |
do {} while (c) |
after the body | 1 |
Where it is the right loop
The pattern is always the same: act first, then decide whether to act again.
Reading until a sentinel
You cannot know whether to stop before you have read something:
const chunks = ['data', 'data', ''];
let i = 0;
let chunk;
do {
chunk = chunks[i++];
if (chunk) console.log('got', chunk); // got data / got data
} while (chunk);
With a while you would have to duplicate the read — once before the loop to prime the condition,
and once inside it. That duplication is the smell do...while removes.
Retrying, where the first attempt is not a retry
async function withRetries(fn, max = 3) {
let attempt = 0;
let lastError;
do {
attempt += 1;
try {
return await fn();
} catch (error) {
lastError = error;
}
} while (attempt < max);
throw lastError;
}
The first call is unconditional — you always try once — and only the repeats are conditional. That is
exactly the asymmetry do...while encodes.
Generating until the value is acceptable
function rollDifferentFrom(previous) {
let roll;
do {
roll = 1 + Math.floor(Math.random() * 6);
} while (roll === previous);
return roll;
}
console.log(rollDifferentFrom(3) !== 3); // true
You have to roll before you can know whether to roll again.
Walking digits off a number
function digits(n) {
const out = [];
do {
out.unshift(n % 10);
n = Math.floor(n / 10);
} while (n > 0);
return out;
}
console.log(digits(407)); // [4, 0, 7]
console.log(digits(0)); // [0] ← a `while` would have returned []
digits(0) is the whole argument. With while (n > 0) the loop never runs and zero has no digits,
which is wrong. The one guaranteed pass is the fix.
break and continue
Both work, with one wrinkle worth knowing: continue jumps to the condition, not past it. So
unlike in a while, a continue here cannot skip the check.
let i = 0;
do {
i += 1;
if (i === 2) continue; // jumps to `while (i < 4)`, which still runs
console.log(i); // 1 / 3 / 4
} while (i < 4);
break leaves immediately and skips the final condition check:
let n = 0;
do {
n += 1;
if (n === 2) break;
} while (true);
console.log(n); // 2
Common mistakes
Forgetting the semicolon
Mistake. } while (n > 0) with no ;, followed by a line starting with ( or [.
Why it fails. Automatic semicolon insertion does not always rescue you, and the next line can be
parsed as a continuation of the expression.
What to do instead. Always terminate it: } while (n > 0);.
Using it when the body might legitimately run zero times
Mistake. do { send(queue.shift()); } while (queue.length) on a queue that can be empty.
Why it fails. The guaranteed first pass sends undefined before the condition is ever consulted.
What to do instead. while (queue.length). Reach for do...while only when the first pass is
genuinely unconditional.
Declaring the loop variable inside the body
Mistake. do { const chunk = read(); } while (chunk);
Why it fails. const is block-scoped to the body, so the condition cannot see it — a
ReferenceError, which is a surprise because the while looks like it is inside the braces.
What to do instead. Declare it with let outside the loop and assign inside, as in the sentinel
example above.
Check yourself
One question from the bank on what you just read. Answering here does not affect your quiz history.
while and do...while look almost identical but are not interchangeable.
What does this log?
let i = 10;
do {
console.log(i);
i++;
} while (i < 5);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.