JavaScript
This page explains while and do...while loops, focusing on when their conditions are checked.
Goal: choose the right loop, update its state, and avoid accidental infinite loops.
while
Loops repeat a block while a condition remains true. A while loop checks the condition before each iteration, so it may run zero times.
JavaScript
let count = 1;
let total = 0;
while (count <= 100) {
total += count;
count += 1; // make progress toward the condition becoming false
}
console.log(total); // 5050do...while
A do...while loop runs its block first and checks the condition afterward. It always runs at least once, even when the condition is initially false.
JavaScript
let answer;
do {
answer = "default";
console.log(answer);
} while (false); // the block has already run onceHow to choose
- Use
whilewhen the work should happen only if the condition is already true. - Use
do...whilewhen the work must happen once before deciding whether to repeat, such as a prompt-and-check flow. - Update a value used by the condition, or use a clear exit, so the loop can finish.
- Keep the condition and state update easy to read; this prevents infinite loops.