JavaScript•Loops
JavaScript While and Do...While Loops with Examples
Learn the difference between pre-test while loops and post-test do...while loops that guarantee at least one execution.
Syntax
while (condition) {}
do {} while (condition);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| while | Loop | Evaluates condition before running the body. |
| do...while | Loop | Executes body first, then evaluates condition. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing JavaScript locally:
// While Loop vs Do...While Loop
let countdown = 3;
console.log("--- While Countdown ---");
while (countdown > 0) {
console.log("T-minus " + countdown + "...");
countdown--;
}
console.log("Blast off! 🚀");
// do...while runs at least once even if condition is false
let attempts = 0;
do {
attempts++;
console.log("\nAttempted execution (guaranteed once):", attempts);
} while (attempts < 1);Expected Output:
--- While Countdown --- T-minus 3... T-minus 2... T-minus 1... Blast off! 🚀 Attempted execution (guaranteed once): 1
How It Works: Step-by-Step
- Lines 4-7: Decrements counter on each iteration until zero.
- Lines 12-15: do...while executes its block before checking the condition.
Key Concepts
- while checks the condition first; if false initially, it never executes.
- do...while executes the loop body once unconditionally before evaluating the condition.
- Always ensure the condition variable is mutated inside the loop body to avoid infinite loops.
Common Mistake: Creating an infinite loop by forgetting to decrement/increment counter
Failing to mutate the condition variable freezes the thread and browser/server process.
❌ Incorrect
let i = 0;
while (i < 5) {
console.log(i); // i is never incremented!
}✅ Correct
let i = 0;
while (i < 5) {
console.log(i);
i++;
}Related JavaScript Tutorials & Compiler
JavaScript For Loops, for...of, and for...in Iteration
Master classical for loops, for...of for iterable items, and for...in for object properties.
JavaScript Break and Continue Statements in Loops
Interrupt or skip loop iterations with break and continue statements.
JavaScript If...Else, Ternary Operator, and Branching
Control code execution based on conditions using if, else if, else, and ternary expressions.
JavaScript Online Compiler
Open in Compilra IDE
Run and test JavaScript on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.