JavaScript:JavaScript While and Do...While Loops with Examples
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:

ParameterTypeDescription
whileLoopEvaluates condition before running the body.
do...whileLoopExecutes body first, then evaluates condition.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler