DevPath · Learn to code ESPTEN

Loops

while and do...while

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 becomes false, and the program spins forever and hangs. Every time you write a while, 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?

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);
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← The classic for loopfor...of, for...in, break and continue →