While and Do-While Loops — When You Don't Know the Count
For loops are great when you know how many times to loop. But what if you don't? While loops keep running until a condition changes — perfect for user input, game loops, and waiting for events.
Day 22 / 180
Beginner Phase
🕐12 min read
💻7 code examples
🎯3 practice tasks
Here is a situation where a for loop doesn't work well:
When you don't know the count
// ❌ For loop requires knowing how many times to loopfor (let i = 0; i < ???; i++) { // What goes here?// Keep rolling dice until you get a 6// You don't know how many rolls it will take!
}
// ✅ While loop — perfect for unknown countslet dice = 0;
let rolls = 0;
while (dice !== 6) {
dice = Math.floor(Math.random() * 6) + 1;
rolls++;
console.log(`Roll ${rolls}: ${dice}`);
}
console.log(`Got a 6 after ${rolls} rolls!`);
While loops are your go-to when you don't know exactly how many times you need to repeat. They keep running "while" a condition is true. Today I'll show you how while and do-while loops work, when to use them, and how to avoid infinite loops that crash your browser.
1. The Problem — Unknown Iteration Count
For loops require you to know how many times to loop. But many real-world scenarios have unknown counts:
When For Loops Fall Short
// Scenarios where you don't know the count:// 1. Keep prompting user until they enter valid input// (You don't know how many attempts they'll need)// 2. Keep generating random numbers until you get a specific value// (Could be 1 try or 100 tries)// 3. Process data until a certain condition is met// (Keep dividing until number becomes 0)// 4. Game loops that run until the player loses// (Don't know how long the game will last)// 5. Reading data from a stream until it ends// (Don't know the total size)// While loops handle all of these perfectly!
💡 The key insight: Use for loops when you know the exact number of iterations (or can calculate it). Use while loops when the number of iterations depends on a condition that changes during execution.
2. While Loop Syntax — Check First, Then Execute
The while loop checks the condition before each iteration. If the condition is false initially, the loop never runs:
While Loop Examples
// Syntax: while (condition) { code to repeat }// Example 1: Count from 1 to 5let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
// Output: 1, 2, 3, 4, 5// Example 2: Sum numbers until you reach 100let sum = 0;
let num = 1;
while (sum < 100) {
sum += num;
num++;
}
console.log(`Sum reached ${sum} after ${num - 1} numbers`);
// Example 3: Keep doubling until exceeding 1000let value = 1;
while (value < 1000) {
console.log(value);
value *= 2;
}
// Output: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512// Example 4: Condition that starts false (loop never runs)let x = 10;
while (x < 5) {
console.log("This will never print"); // Skipped!
}
3. Do-While Loop — Execute First, Then Check
The do-while loop is different: it executes the code block first, then checks the condition. This guarantees at least one execution, even if the condition is false:
Do-While Loop Examples
// Syntax: do { code } while (condition);// Example 1: Runs at least once even if condition is falselet i = 10;
do {
console.log(`This runs once: i = ${i}`);
i++;
} while (i < 5);
// Output: "This runs once: i = 10" (even though 10 is not < 5)// Example 2: Menu system (always shows menu at least once)let choice;
do {
console.log("1. Start Game");
console.log("2. Settings");
console.log("3. Exit");
choice = 3; // Simulate user input
} while (choice !== 3);
console.log("Goodbye!");
// Example 3: Prompt until valid input (simulated)let password;
let attempts = 0;
do {
password = "secret"; // Simulate correct input on first try
attempts++;
if (password !== "secret") {
console.log("Wrong password! Try again.");
}
} while (password !== "secret");
console.log(`Access granted after ${attempts} attempt(s)`);
⚠️ Key Difference: While vs Do-While
While: Checks condition first → may never run. Do-While: Runs code first → always runs at least once.
Use do-while when you need to guarantee at least one execution (like showing a menu or prompting for input).
4. While vs For — When to Use Which
Both loops can often do the same job, but each is better suited for different scenarios:
For vs While Comparison
// SAME TASK: Loop through array (can use either)// For loop — cleaner when you know the countlet fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// While loop — works but more verboselet i = 0;
while (i < fruits.length) {
console.log(fruits[i]);
i++;
}
// --- WHEN TO USE FOR LOOP ---// ✅ Known number of iterationsfor (let i = 0; i < 100; i++) { ... }
// ✅ Looping through arrays with indexfor (let i = 0; i < arr.length; i++) { ... }
// ✅ Counting up or down by a specific stepfor (let i = 10; i >= 0; i -= 2) { ... }
// --- WHEN TO USE WHILE LOOP ---// ✅ Unknown number of iterationswhile (dice !== 6) { dice = roll(); }
// ✅ Waiting for a condition to changewhile (!userClicked) { wait(); }
// ✅ When loop variable updates are complexwhile (num > 0) {
// complex logic that may update num in multiple ways
num = complexOperation(num);
}
5. Infinite Loops — The Silent Killer ⚠️
An infinite loop never stops because the condition never becomes false. This freezes your browser tab! Always ensure your loop condition will eventually become false:
Infinite Loops — DANGER!
// ❌ INFINITE LOOP 1: Condition never changeslet i = 0;
while (i < 10) {
console.log(i);
// Forgot to increment i → i is always 0!
}
// This will run forever! 💀// ✅ FIX: Always update the variablelet i = 0;
while (i < 10) {
console.log(i);
i++; // ← Crucial!
}
// ❌ INFINITE LOOP 2: Condition always truewhile (true) {
console.log("This will run forever");
}
// ✅ FIX: Use break to exit (but be careful!)let count = 0;
while (true) {
console.log(count);
count++;
if (count >= 10) break; // Exit condition
}
// ❌ INFINITE LOOP 3: Wrong comparisonlet num = 10;
while (num > 0) {
console.log(num);
num++; // Oops! Increasing makes it never reach 0
}
// ✅ FIX: Decrease when counting downwhile (num > 0) {
console.log(num);
num--; // ← Decrease towards 0
}
🚨 If You Create an Infinite Loop:
1. Your browser tab will freeze/stop responding.
2. Close the tab (or kill the browser process).
3. Fix the condition before running again. Always test loops with small counts first!
6. Common Mistakes to Avoid
Mistakes & Fixes
// ❌ MISTAKE 1: Semicolon after while conditionlet i = 0;
while (i < 5); { // ← semicolon ends the loop!
console.log(i);
i++;
}
// Loop body never executes (infinite empty loop)// ✅ FIX: No semicolonwhile (i < 5) {
console.log(i);
i++;
}
// ❌ MISTAKE 2: Forgetting to initialize variablewhile (count < 10) { // count is undefined!
console.log(count);
count++;
}
// ✅ FIX: Initialize before looplet count = 0;
while (count < 10) {
console.log(count);
count++;
}
// ❌ MISTAKE 3: Do-while missing semicolondo {
console.log("Hello");
} while (false) // ← Missing semicolon (syntax error)// ✅ FIX: Add semicolon after whiledo {
console.log("Hello");
} while (false); // ← Semicolon required!// ❌ MISTAKE 4: Using = instead of === in conditionlet running = true;
while (running = false) { // Assignment, not comparison!
console.log("Never runs");
}
// ✅ FIX: Use comparison operatorwhile (running === false) { ... }
// Or better:while (!running) { ... }
7. Try It Yourself — While Loop Playground
Experiment with while loops below. See how they keep running until a condition is met.
✏️ While Loop Playground
HTML
JAVASCRIPT
LIVE PREVIEW
💡 Click the button — see how while loops work!
8. Practice Tasks
Task 1 — Easy: Countdown Timer
Write a while loop that counts down from 10 to 1 and then prints "Blast off!". Use a variable that decreases each iteration.
Task 2 — Medium: Keep Guessing
Create a number guessing game. Generate a random number between 1-100. Use a while loop to keep asking the user for guesses until they get it right. Count and display the number of attempts.
Task 3 — Hard: Do-While Menu System
Create a calculator menu using do-while. Display options: 1. Add, 2. Subtract, 3. Multiply, 4. Divide, 5. Exit. Keep showing the menu until user selects exit. Use do-while to ensure menu shows at least once.