Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Statements and Declarations

The do...while statement

Reference for the JavaScript do...while loop: body runs first, condition is checked after, the optional semicolon, continue behavior and typical uses.

The do...while statement runs its body once, then checks the condition, and repeats while the condition is truthy. The body therefore always runs at least once, which is the only difference from while.

It suits "do something, then decide whether to continue" tasks: reading a first value, retrying an operation, or generating a candidate until it is acceptable.

JavaScript
do {
  attempt();
} while (failed);

Try it

JS Runs once even when false

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Retry until success, and continue

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
do {
  statement
} while (condition);
Part Description
statement The body, executed at least once.
condition Evaluated after each pass; the loop repeats while it is truthy.

Usage notes

  • Check last. The condition sees the state after the body has run, so variables set inside the body can be used in it. Declare them outside the loop, since a let inside the block is not visible in the condition.
  • Semicolon. The final semicolon after while (...) is optional because of automatic semicolon insertion, but include it for clarity. It is specific to this loop; other loops do not end with one.
  • continue jumps to the condition check, not to the top of the body. As in while, any update written after the continue line is skipped for that pass.
  • break exits the loop immediately.
  • Infinite loops happen when nothing in the body can make the condition falsy.
  • Less common than for and while; many developers prefer while (true) with a break in the middle when the exit test falls in the middle of the body.
  • Single-statement body is allowed without braces, but braces are recommended.

Browser support

Supported in every JavaScript engine.