Run At Least Once
do...while runs the body first and checks the condition afterward.
Use it when the body must execute at least once.
JavaScript Tutorial
The do...while loop runs its body once before checking the condition.
This guarantees at least one iteration.
Some tasks must run at least once, such as showing a menu or validating input.
do...while matches that pattern without extra boilerplate.
do { ... } while (condition)let i = 0;
do {
console.log(i);
i++;
} while (i < 3);The body runs before the condition check.
let count = 0;
do {
console.log("Runs once");
} while (count > 0);Even though the condition is false, it runs once.
do...while runs the body first and checks the condition afterward.
Use it when the body must execute at least once.
It is useful for input validation and menus that must show at least once.
The loop continues as long as the condition remains true.
Just like while, make sure the condition can become false.
Update counters or state inside the loop.
let choice = "";
let attempts = 0;
do {
attempts++;
choice = attempts === 2 ? "exit" : "stay";
} while (choice !== "exit");
console.log(choice);Common for menu interactions and retries.
let value = -1;
do {
value++;
} while (value < 0);
console.log(value);Ensure a validation step happens at least once.
Without
let i = 0;
console.log(i);
i++;
while (i < 1) {
console.log(i);
i++;
}With
let i = 0;
do {
console.log(i);
i++;
} while (i < 1);Remember do...while checks after the body runs.
Update counters or state to avoid infinite loops.
Use while if the body should not always run.
After running the body once.
When you need the loop body to run at least once.
Ensure the condition can become false.
Practice: Use do...while to print numbers from 1 to 3.
let i = 1;
// TODO: print 1, 2, 3 using do...while
One Possible Solution
let i = 1;
do {
console.log(i);
i++;
} while (i <= 3);do...while runs the body at least once before checking the condition.
When you need the body to run at least once, like menus or input validation.
Yes, but you would need an extra first run before the loop.
Try a do...while loop and change the condition to see the effect.