Topic 31 of 87
do...while Loop
Overview
The do...while loop is a variant of the while loop. The crucial difference is that this loop will execute the code block ONCE before checking if the condition is true.
After the first execution, it will repeat the loop as long as the condition evaluates to true.
Syntax
Basic do...while
javascript
let i = 10;
// This code block runs immediately, regardless of the condition!
do {
console.log("This prints at least once!");
i++;
} while (i < 5);
// Loop ends immediately after the first check because 11 is not < 5.Common Pitfalls
- It's very rarely used in modern JavaScript. Most developers prefer the standard
whileloop and handle the initialization data appropriately to ensure readability.
Interview Questions
Q:
What is the primary difference between a
while and a do...while loop?A:
A while loop checks the condition before executing the block. A do...while loop executes the block first, and checks the condition after. Therefore, a do...while loop is guaranteed to run at least once.
Real-World Example
Prompting a user for a password or PIN. They must be prompted at least once, and if it's incorrect, they are prompted again.
example
javascript
let pwd;
do {
pwd = prompt("Enter your password:");
} while (pwd !== "secret123");Check Your Knowledge
Test your understanding of do...while Loop with these quick questions.