Chapter V · Control Flow

The do...while Loop

do...while is like while, but it checks the condition after the body runs — so the body is always guaranteed to execute at least once.

01 What Is do...while?

do...while flips the order of while: the block runs first, and the condition is evaluated afterward, at the bottom. That ordering means the loop always runs one full iteration before it can possibly decide to stop — useful whenever "do the thing, then decide if you need to repeat" better matches the real-world logic than "check first, maybe do the thing".

02 Simple Example

A block that runs once even though its condition is immediately false.

do-while.js
let count = 0;\n\ndo {\n  console.log("Runs at least once:", count);\n  count++;\n} while (count < 0);

count < 0 is false from the start, so a plain while loop with the same condition would never run. Because this is do...while, the block still executes exactly once before the (failing) check happens.

03 How It Works

Execution enters the block unconditionally on the first pass — there's no gate at the top. Only after the block finishes does the engine evaluate the while condition; a truthy result sends execution back to the top of the block, a falsy one ends the loop.

04 Step-by-Step

  1. Run the code block once, unconditionally.

  2. Evaluate the condition in the while(...) clause.

  3. If true, jump back to the top of the block and repeat.

  4. If false, exit the loop.

05 Common Mistakes & Edge Cases

Rarely used, easily forgotten. do...while is uncommon enough in everyday code that its trailing semicolon after while(...) — required, unlike a regular while loop — is a frequent typo source.

A realistic use case is input validation or retry logic: prompt once, then keep re-prompting only if the result is invalid — the first attempt should always happen regardless of any prior state.

06 Mental Model

"Tasting the soup first, then deciding whether it needs more salt — you always taste it at least once."

07 Interview Questions

Q: When would do...while behave differently from an equivalent while loop?

Only when the condition is false on the very first check — that's the one case where do...while still runs the body once and while doesn't run it at all. With a condition that's true initially, they behave identically.

Key Takeaway

do...while guarantees exactly one run of the block before the condition is ever checked, which makes it the right tool specifically when "always run once, then maybe repeat" is the actual requirement.

Related Concepts