Example 1 — Runs once when condition is false
Unlike while, the body still runs.
JavaScript
do {
console.log("once");
} while (false); How It Works
- Body executes.
- Condition false → stop.
do...while runs the body first, then checks the condition. Use it when you need at least one pass (menus, prompts, read-until-valid patterns).
let n = 0;
do {
console.log(n);
n++;
} while (n < 2); Unlike while, the body still runs.
do {
console.log("once");
} while (false); Attempt, then decide whether to continue.
let tries = 0;
do {
tries++;
console.log("try " + tries);
} while (tries < 3); If zero passes are OK, while is clearer.
console.log("use while when zero passes are fine"); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful