The JavaScript do...while statement
The do...while loop runs its body first, then checks the condition — so the body always executes at least once, even if the condition is false to begin with. Use it when you must do something before you can test whether to repeat, like prompting for input until it's valid. Contrast with while, which checks first.
Overview
do...while is a loop with the condition at the bottom. It runs the body, then evaluates the condition; if it's true, it loops again. The defining consequence is that the body always runs at least once, regardless of the condition — which is exactly the opposite of a while loop, where a false condition means the body never runs at all.
That "at least once" guarantee is what it's for. The textbook case is asking for something and then validating it: do the prompt, then check whether the answer was acceptable, and repeat until it is. Any "act first, then decide whether to repeat" pattern fits.
It's less common than the other loops, partly because many such cases can be restructured with a plain while and partly because reading the condition at the end takes a moment to parse. Don't forget the semicolon after the while (...) — it's required here, unlike a regular while loop. As always, break and continue work inside it.
Syntax
do {
// runs at least once
} while (condition);
let n = 0;
do {
n++;
} while (n < 5); // n ends at 5
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
let n = 1;
const seen = [];
do {
seen.push(n);
n *= 3;
} while (n < 50);
document.getElementById('out').textContent = seen.join(', '); // 1, 3, 9, 27
</script>
Best practices
- Use it when the body must run at least once before the condition is checked.
- Remember the semicolon after
while (...)— it's required fordo...while. - Ensure the condition can eventually become false to avoid an infinite loop.
- Prefer a plain while when a zero-iteration case is valid.
Frequently asked questions
What is the difference between do...while and while?
do...while checks the condition after the body, so it always runs at least once; while checks first, so it may run zero times.When should I use do...while?
Does do...while need a semicolon?
while (condition); at the end requires a semicolon, unlike a standard while loop.