While a for loop is ideal when you know exactly how many times to repeat something, the while and do...while loops are built for the opposite case: repeating code until some condition becomes false, without necessarily knowing in advance how many iterations that will take.
The while Loop
A while loop checks its condition before each iteration. If the condition is false from the very start, the loop body never runs at all.
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
Output:
1
2
3
4
5
Notice the counter variable has to be declared and incremented manually, unlike a for loop where that's built into the syntax. Forgetting to update the counter is the most common cause of an accidental infinite loop.
The do...while Loop
A do...while loop is nearly identical, but it checks its condition after running the body — which guarantees the loop body executes at least once, even if the condition is false immediately.
let attempts = 0;
const maxAttempts = 3;
do {
attempts++;
console.log(`Attempt ${attempts}`);
} while (attempts < maxAttempts);
Output:
Attempt 1
Attempt 2
Attempt 3
This "run at least once" guarantee is useful for things like menu prompts or retry logic, where you always want to attempt the action at least a single time before checking whether to continue.
while vs do...while: The Key Difference
let x = 10;
while (x < 5) {
console.log("while: this never runs");
}
do {
console.log("do...while: this runs once, even though the condition is false");
} while (x < 5);
Output:
do...while: this runs once, even though the condition is false
In practice, plain while loops are far more common than do...while — reach for do...while specifically when the "run it first, then decide whether to repeat" behavior matches your use case.
