A do-while loop is an exit-controlled loop in JavaScript. Unlike the while loop, the condition is evaluated at the bottom of the loop body. Consequently, the body of a do-while loop is guaranteed to execute at least once, regardless of whether the initial test condition is true or false.
// Guaranteed Execution Demo: Condition is FALSE from the start!
let initialScore = 100;
do {
console.log("This message prints once even though 100 > 500 is false!");
} while (initialScore > 500);
Because the user must enter data at least once before you can validate it, do-while is the canonical choice for validation routines:
// Simulating pin-entry retry validation
let attempts = 0;
let pinIsValid = false;
do {
attempts++;
// Simulate checking a pin code
console.log(`Prompting User: Attempt #${attempts}`);
if (attempts === 3) {
pinIsValid = true; // User typed correct pin on 3rd attempt
}
} while (!pinIsValid && attempts < 5);
console.log("Access status:", pinIsValid ? "Granted" : "Locked");
Exam Question: "Differentiate between while loop and do-while loop with an execution comparison."
| Feature | While Loop | Do-While Loop |
|---|---|---|
| Loop Category | Entry-controlled (Pre-test) | Exit-controlled (Post-test) |
| Minimum Iterations | 0 (May never execute) | 1 (Guaranteed at least once) |
| Semicolon Requirement | No trailing semicolon: while() { } |
Requires trailing semicolon: do { } while(); |
What is the most popular, compact loop when the number of iterations is known in advance? Proceed to: JavaScript For Loop: Structure, Traversal & Nesting →
Accelerate your JavaScript mastery by studying these tightly connected core tutorials:
Entry-controlled loop comparison.
Standard counting iteration loops.
Controlling loop execution cycles.