The while loop
Sometimes you don't know how many rounds you'll need: you only know when to
stop. Picture a countdown before a launch, or reading messages "while there are
unread ones left". That's what while is for, repeating while the condition
is true:
let count = 3;
while (count > 0) {
console.log("Remaining:", count);
count--;
}
console.log("Liftoff! 🚀");
⚠️ Classic trap: the infinite loop. It happens to all of us: you forget the
count--, the condition never becomesfalse, and the program spins forever and hangs. Every time you write awhile, ask yourself: "which line makes this end someday?".
The do...while loop
It's like while, but it checks the condition at the end. This guarantees the
body runs at least once, even if the condition is false from the
start:
let n = 10;
do {
console.log("This runs once even if n is already large");
n++;
} while (n < 5);
for or while?
for: known number of repetitions (go from 1 to 100).while: repeat until something happens (read data until it runs out).do...while: same aswhile, but you need to run the body at least once (show a menu and ask for it again).
Examples
Countdown with while
let count = 3;
while (count > 0) {
console.log(count);
count--;
}
console.log("Done!");
do...while runs at least once
let attempts = 0;
do {
console.log("Attempt", attempts);
attempts++;
} while (attempts < 3);