Use a while loop when you do not know in advance how many times to repeat. It runs as long as a condition is true.
let count = 0;
while (count < 3) {
console.log("count is", count);
count++;
}
The condition is checked before each round. Something inside the loop must eventually make it false, otherwise it runs forever.
A realistic example
Keep halving a number until it is small.
let value = 100;
let steps = 0;
while (value > 1) {
value = value / 2;
steps++;
}
console.log(steps); // → 7
do…while
A do...while loop checks the condition after each round, so the body always runs at least once.
let attempts = 0;
do {
attempts++;
console.log("Attempt", attempts);
} while (attempts < 3);
Compare with a while whose condition is false from the start:
let n = 10;
while (n < 5) {
console.log("while body"); // never runs
}
do {
console.log("do body"); // runs once
} while (n < 5);
Typical uses
- Reading data until none is left.
- Retrying something until it succeeds (with a limit!).
- Algorithms where the number of steps depends on the data.
Safety: always have a way out
let tries = 0;
const maxTries = 5;
while (tries < maxTries) {
tries++;
if (tries === 3) {
console.log("Found it on try", tries);
break;
}
}
Adding a maximum count guards against accidental infinite loops. Keep the Try it editor away from while (true) without a break: it would freeze the example.
The forever loop
while (x < 10) with no change to x inside never ends and freezes the browser tab. Always check that your loop moves toward its end.