References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript do...while statement

Statement JavaScript All modern browsers Updated
Quick answer

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

Live 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 for do...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?
When you need to perform an action before you can decide whether to repeat — like prompting for input and validating it.
Does do...while need a semicolon?
Yes. The while (condition); at the end requires a semicolon, unlike a standard while loop.
Can I use break in a do...while loop?
Yes. Both break and continue work inside it.