JavaScript
This page explains how a do...while loop runs its body once before checking its condition.
Goal: use do...while when an action must happen at least once, while still controlling when repetition stops.
do...while
A do...while loop executes its block first, then checks the condition. If the condition is true, it repeats. Therefore, the block always runs at least once.
JavaScript
do {
// code to run
} while (condition);A counting example
JavaScript
let count = 0;
do {
console.log(`Count: ${count}`);
count += 1;
} while (count < 5);The body prints 0 through 4. Even if the condition were false before the loop started, the first print would still happen.
When is it useful?
- Ask for input once, then repeat only when the input is invalid.
- Show or perform an initial action before deciding whether to continue.
- Update the state used by the condition so the loop can finish.
- Use
whileinstead when the body should run zero times when the initial condition is false.