Understanding the do...while Loop in JavaScript
📍 What is do...while?
The do...while loop is a control structure in JavaScript that executes the code block at least once and then repeats it as long as the condition is true. It guarantees one execution before checking the condition. 🎯
>>“Run first, check later — that's the motto of the do...while loop.” 🔂
📘 Syntax
do...while Syntax
do {
// block of code
} while (condition);Unlike while, which checks the condition before the loop runs, do...while checks the condition after the first run. ✅
📦 Example: Print 1 to 5
Simple do...while Example
let i = 1;
do {
console.log("🔢 Count:", i);
i++;
} while (i <= 5);Even if i starts at a value that fails the condition, the block still runs once before the check. Let’s see that below! 🔍
⚠️ Always Runs Once
Condition False at Start
let i = 10;
do {
console.log("✅ This runs once even though i > 5");
} while (i <= 5);Note
Even though i <= 5 is false, the message will print once. This is the key behavior of do...while. 🧠
🧰 Real World Use Case
do...while loops are useful when you want to ensure the user sees a message or prompt at least once.
User Input Simulation
let input;
do {
input = prompt("Enter a number greater than 10:");
} while (input <= 10);
alert("🎉 Thank you!");Note
This loop keeps asking until the user provides a number greater than 10. But the prompt always shows at least once. 🙋
✅ Use Cases
- Collecting user input where at least one attempt is required
- Initializing values or configurations
- Executing code with guaranteed one-time run
📚 Resources to Explore
>>“When you need to try first and ask questions later — reach for do...while.” 🚀