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.
do { attempt(); } while (failed);
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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
letinside 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. continuejumps to the condition check, not to the top of the body. As inwhile, any update written after thecontinueline is skipped for that pass.breakexits the loop immediately.- Infinite loops happen when nothing in the body can make the condition falsy.
- Less common than
forandwhile; many developers preferwhile (true)with abreakin 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.
Related
while,for,break,continue- Lessons: while loops