While Loop Syntax
A while loop checks its condition before each iteration. If the condition is false from the start, the body never executes.
// 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");
}
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.
// 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!");
}
While vs do...while Use Cases
| Scenario | Use while | Use do...while |
|---|---|---|
| Loop may run zero times | Yes | No |
| Body must run at least once | No | Yes |
| User input validation | Less natural | Natural fit |
| File/stream reading | Common | Possible |
| Game loop (play first, check later) | Possible | Perfect |
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.
// 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);
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".
// 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);
Countdown Timer Pattern
function countdown(from) {
let i = from;
while (i > 0) {
console.log(i + "...");
i--;
}
console.log("Liftoff! π");
}
countdown(5);
While with Complex Conditions
// 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);
Converting for to while
Every for loop can be rewritten as a while loop β they are equivalent in power.
// 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
}
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
| Feature | while | do...while | for |
|---|---|---|---|
| Condition checked | Before body | After body | Before body |
| Minimum executions | 0 | 1 | 0 |
| Known iteration count | Possible | Possible | Best fit |
| Unknown iteration count | Best fit | Good | Awkward |
| Init/update in header | No | No | Yes |
ποΈ 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
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.
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.
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.