while & do...while Loops: Condition-Driven Iterationwhile and do...while loops execute a code block as long as a specified condition evaluates to true. While while checks the condition before executing the loop body, do...while executes the body at least once before testing the condition.
while vs do...while Flowchartflowchart TD
subgraph WhileLoop ["while (condition)"]
WCond{"Check Condition"} -- "True" --> WBody["Execute Body"] --> WCond
WCond -- "False" --> WExit["Exit Loop"]
end
subgraph DoWhileLoop ["do { ... } while (condition)"]
DBody["Execute Body (Always 1st Time)"] --> DCond{"Check Condition"}
DCond -- "True" --> DBody
DCond -- "False" --> DExit["Exit Loop"]
end
| Loop Type | Minimum Iterations | Condition Evaluation Time | Primary Use Case |
|---|---|---|---|
while |
0 (May never run if initially false) |
Before body execution | Indeterminate loop count (waiting for flag/event). |
do...while |
1 (Guaranteed at least once) |
After body execution | Interactive prompts, menu loops, polling tasks. |
// Demonstrating while vs do...while loops
// 1. Standard while loop (Polling simulation)
let retryAttempts = 0;
const MAX_RETRIES = 3;
let success = false;
console.log("--- Polling with while loop ---");
while (retryAttempts < MAX_RETRIES && !success) {
retryAttempts++;
console.log(`Connection attempt #${retryAttempts}...`);
if (retryAttempts === 2) {
success = true;
console.log("Connection Established!");
}
}
// 2. do...while loop (Guaranteed first execution)
let inputValid = false;
let attempts = 0;
console.log("
--- Form Validation with do...while loop ---");
do {
attempts++;
console.log(`Processing validation attempt #${attempts}`);
if (attempts >= 1) {
inputValid = true; // Input validated on first pass
}
} while (!inputValid);
false.while for Queue Drain Operations: while (queue.length > 0) is the canonical pattern for processing task queues.do...while Semicolon: Remember that do { ... } while (condition); requires a trailing semicolon after the closing parenthesis.Write a while loop that continuously divides a number n = 100 by 2 until n becomes less than 10.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.