Ad – 728Γ—90
πŸ”€ Control Flow

JavaScript While Loop – while and do...while

While loops are perfect when you don't know in advance how many iterations you'll need. Learn the while loop, the do...while variant that guarantees at least one execution, and best practices to avoid infinite loops.

⏱️ 15 min read 🎯 Beginner πŸ“… Updated 2026

While Loop Syntax

A while loop checks its condition before each iteration. If the condition is false from the start, the body never executes.

JavaScript
// Basic while loop
let count = 0;
while (count < 5) {
  console.log("Count: " + count);
  count++; // Update β€” must move toward exit condition!
}

// Condition false from start β€” body never runs
let n = 10;
while (n < 5) {
  console.log("This never prints");
}
β–Ά Output
Count: 0 Count: 1 Count: 2 Count: 3 Count: 4

do...while Loop

A do...while loop checks its condition after each iteration. The body always runs at least once, even if the condition is initially false.

JavaScript
// do...while β€” body runs before condition is checked
let x = 10;
do {
  console.log("x = " + x);  // Prints once even though x >= 5
  x++;
} while (x < 5);

// Practical: show a menu at least once
function showMenu() {
  let choice;
  do {
    // In a browser you'd use prompt(); here we simulate
    choice = "quit"; // Simulating user typing "quit"
    console.log("Menu shown. User chose: " + choice);
  } while (choice !== "quit");
  console.log("Goodbye!");
}
β–Ά Output
x = 10 Menu shown. User chose: quit Goodbye!

While vs do...while Use Cases

ScenarioUse whileUse do...while
Loop may run zero timesYesNo
Body must run at least onceNoYes
User input validationLess naturalNatural fit
File/stream readingCommonPossible
Game loop (play first, check later)PossiblePerfect

Infinite Loop Prevention

A loop that never terminates will freeze your program. The two main causes are a missing update statement and a condition that never becomes false.

JavaScript
// DANGER β€” Infinite loop! (Do NOT run)
// let i = 0;
// while (i < 10) {
//   console.log(i);
//   // Forgot to increment i!
// }

// Safe β€” safety counter as a guard
let safetyCounter = 0;
const MAX_ITERATIONS = 1000;
let found = false;

while (!found && safetyCounter < MAX_ITERATIONS) {
  safetyCounter++;
  // ... search logic here ...
  if (safetyCounter === 5) found = true; // Simulated find
}

console.log("Stopped after " + safetyCounter + " iterations. Found: " + found);
β–Ά Output
Stopped after 5 iterations. Found: true
🚫
Infinite Loop Will Crash Your Tab

In a browser, an infinite loop blocks the main thread and freezes the tab. Node.js will spin the CPU at 100%. Always ensure your loop condition will eventually become false, or use a safety counter limit.

User Input Validation Loop

A do...while loop is the idiomatic pattern for "keep asking until valid input is received".

JavaScript
// Simulated prompt function (in browser use window.prompt)
const inputs = ["abc", "-5", "25"]; // Simulated user inputs
let inputIndex = 0;

function simulatedPrompt(msg) {
  console.log(msg);
  return inputs[inputIndex++];
}

let age;
do {
  const input = simulatedPrompt("Enter your age (1-120):");
  age = parseInt(input);
  if (isNaN(age) || age < 1 || age > 120) {
    console.log("Invalid input. Try again.");
  }
} while (isNaN(age) || age < 1 || age > 120);

console.log("Valid age entered: " + age);
β–Ά Output
Enter your age (1-120): Invalid input. Try again. Enter your age (1-120): Invalid input. Try again. Enter your age (1-120): Valid age entered: 25

Countdown Timer Pattern

JavaScript
function countdown(from) {
  let i = from;
  while (i > 0) {
    console.log(i + "...");
    i--;
  }
  console.log("Liftoff! πŸš€");
}

countdown(5);
β–Ά Output
5... 4... 3... 2... 1... Liftoff! πŸš€

While with Complex Conditions

JavaScript
// Process queue until empty or error
const queue = ["task1", "task2", "error", "task4"];
let hasError = false;
let processed = [];

while (queue.length > 0 && !hasError) {
  const task = queue.shift();
  if (task === "error") {
    hasError = true;
    console.log("Stopping: error encountered.");
  } else {
    processed.push(task);
    console.log("Processed: " + task);
  }
}

console.log("Processed tasks:", processed);
β–Ά Output
Processed: task1 Processed: task2 Stopping: error encountered. Processed tasks: [ 'task1', 'task2' ]

Converting for to while

Every for loop can be rewritten as a while loop β€” they are equivalent in power.

JavaScript
// Classic for loop
for (let i = 0; i < 3; i++) {
  console.log("for: " + i);
}

// Equivalent while loop
let i = 0;       // Initialization
while (i < 3) {  // Condition
  console.log("while: " + i);
  i++;           // Update
}
β–Ά Output
for: 0 for: 1 for: 2 while: 0 while: 1 while: 2
πŸ’‘
When to Choose while Over for

Use while when the number of iterations depends on a runtime condition, not a known count. Examples: polling until a server responds, processing items from a queue, game loops, and search algorithms.

Loop Comparison Table

Featurewhiledo...whilefor
Condition checkedBefore bodyAfter bodyBefore body
Minimum executions010
Known iteration countPossiblePossibleBest fit
Unknown iteration countBest fitGoodAwkward
Init/update in headerNoNoYes
Ad – 336Γ—280

πŸ‹οΈ Practical Exercise

Write a function sumUntil(target) that uses a while loop to keep adding consecutive integers (1, 2, 3, …) until the running total reaches or exceeds target. Return an object { sum, count }. Test with sumUntil(100).

πŸ”₯ Challenge Exercise

Simulate a simple ATM with a do...while loop:

  • Start with a balance of $500
  • Simulate an array of withdrawal requests: [100, 200, 300, 50]
  • Each iteration: try the next withdrawal; if balance is insufficient, print "Insufficient funds" and stop
  • Keep looping while there are requests AND balance > 0
  • Print the final balance

πŸ“‹ Summary

  • while (condition) {} checks condition before running β€” can run zero times.
  • do {} while (condition) checks condition after β€” always runs at least once.
  • Use do...while for user input validation and "run then check" scenarios.
  • Always update the loop variable or your condition will never become false.
  • Use a safety counter in complex loops to prevent runaway execution.
  • For loops and while loops are interchangeable β€” choose based on readability.

Interview Questions

  • What is the key difference between while and do...while?
  • When would you choose a while loop over a for loop?
  • How do you prevent an infinite loop?
  • Give a real-world use case where do...while is the best choice.
  • What happens if the condition in a while loop is never false?

Frequently Asked Questions

Can I use break inside a while loop?+

Yes, break exits any loop β€” for, while, or do...while β€” immediately. It's often used as a safety exit when a specific condition is met inside the loop body.

Is while (true) ever acceptable?+

Yes, while (true) is common in server event loops, game loops, and daemon processes that intentionally run forever. In these cases, break is used to exit when a shutdown condition is detected.

How is a while loop different from recursion?+

Both repeat work, but loops use iteration (same function frame) while recursion calls itself (new frame per call). Loops don't risk stack overflow; recursion is more elegant for tree traversal and divide-and-conquer problems.