By the end of this lesson, learners will:
do...while loopwhile and for loopsdo...while loops for input validation and repetitiondo...while Loop?A do...while loop is a type of loop that:
This is what makes it different from a regular while loop, which checks the condition before running.
do...whiledo {
// code to run
} while (condition);
The code block runs first, then the condition is checked.
Think of a restaurant feedback form:
The waiter gives you the form before asking if you want to fill it out.
You may return it empty, but you’re handed the form regardless.
This is the logic of do...while: you always get one run, no matter what.
let i = 1;
do {
console.log("Loop run #" + i);
i++;
} while (i <= 3);
Output:
Loop run #1
Loop run #2
Loop run #3
Even though it’s like a while loop, the first iteration happens no matter what.
while Loopwhile:let i = 10;
while (i < 5) {
console.log("This will not run");
}
Output: Nothing — the condition is false from the start.
do...while:let i = 10;
do {
console.log("This runs once, even if i < 5 is false");
} while (i < 5);
Output:
This runs once, even if i < 5 is false
let password;
do {
password = prompt("Enter your password:");
} while (!password);
console.log("Thanks for entering a password!");
The prompt will always appear at least once, even if the user hits cancel or leaves it empty.
let choice;
do {
choice = prompt("Choose 1 for Info, 2 for Help, 0 to Exit");
} while (choice !== "0");
console.log("Goodbye!");
The menu keeps showing until the user types “0”.
Just like other loops, if your condition never becomes false, the do...while loop will run forever.
✅ Always make sure: