While for loops are great when you know exactly how many times to repeat, while and do-while loops are perfect when you want to repeat code as long as a condition is true. They're ideal for validating user input, reading data until done, or repeating actions until a goal is met. Let's master condition-based loops!
While Loop
A while loop repeats code as long as a condition is true. The condition is checked before each iteration.
Syntax
while (condition) {
// Code to repeat
// Must change condition eventually!
}
// Example
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
// Output: 0, 1, 2, 3, 4How While Loops Work
- Check condition
- If true, execute code block
- Go back to step 1
- If false, exit loop
let i = 0;
while (i < 3) {
console.log("Iteration:", i);
i++;
}
// Step by step:
// 1. Check: 0 < 3? Yes → execute
// Output: "Iteration: 0", i becomes 1
// 2. Check: 1 < 3? Yes → execute
// Output: "Iteration: 1", i becomes 2
// 3. Check: 2 < 3? Yes → execute
// Output: "Iteration: 2", i becomes 3
// 4. Check: 3 < 3? No → stopBasic While Loop Examples
// Count to 5
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
// Output: 1, 2, 3, 4, 5
// Countdown
let countdown = 5;
while (countdown > 0) {
console.log(countdown);
countdown--;
}
console.log("Liftoff!");
// Output: 5, 4, 3, 2, 1, Liftoff!
// Sum until threshold
let sum = 0;
let num = 1;
while (sum < 50) {
sum += num;
num++;
}
console.log("Sum:", sum); // 55
console.log("Numbers used:", num - 1); // 10
// Process while condition is met
let password = "";
let attempts = 0;
while (password !== "secret" && attempts < 3) {
// password = prompt("Enter password:");
password = "secret"; // Simulating user input
attempts++;
}
console.log("Attempts:", attempts);While vs For Loop
While loops and for loops can often accomplish the same task, but they're suited for different scenarios.
Choose based on what you know
For Loop (Count-Based)
// For loop - know iterations
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Count-based iteration
let array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
// Clear start and end
for (let i = 1; i <= 10; i++) {
console.log(i * 2);
}While Loop (Condition-Based)
// While loop - unknown iterations
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// Condition-based iteration
let found = false;
let j = 0;
while (!found && j < array.length) {
if (array[j] === 3) found = true;
j++;
}
// Continue until condition met
let sum = 0;
let k = 1;
while (sum < 50) {
sum += k;
k++;
}Use For Loop When:
- You know exact number of iterations
- Iterating through arrays/collections
- Counter-based iteration
- Standard counting patterns
Use While Loop When:
- Number of iterations unknown
- Loop until specific condition met
- Waiting for user input
- Processing until data exhausted
- Game loops and simulations
Do-While Loop
A do-while loop is similar to a while loop, but it checks the condition after executing the code block. This means it always runs at least once.
Syntax
do {
// Code to execute
// Runs at least once!
} while (condition);
// Example
let count = 0;
do {
console.log(count);
count++;
} while (count < 5);
// Output: 0, 1, 2, 3, 4Key Difference: Execute First, Check After
// While loop - might not run at all
let i = 10;
while (i < 5) {
console.log("While:", i); // Never executes
}
console.log("While loop didn't run");
// Do-while loop - always runs once
let j = 10;
do {
console.log("Do-while:", j); // Executes once!
} while (j < 5);
console.log("Do-while ran once");
// Output:
// "While loop didn't run"
// "Do-while: 10"
// "Do-while ran once"Remember: Do-while loops ALWAYS execute at least once because the condition is checked after the code runs. Use this when you need guaranteed first execution.
Do-While Examples
// Menu that must display at least once
let choice;
do {
console.log("Menu:");
console.log("1. New Game");
console.log("2. Load Game");
console.log("3. Exit");
// choice = prompt("Choose option:");
choice = "3"; // Simulating user input
} while (choice !== "3");
console.log("Goodbye!");
// Validate input - must ask at least once
let age;
do {
// age = prompt("Enter your age:");
age = 25; // Simulating valid input
} while (age < 0 || age > 120);
console.log("Valid age:", age);
// Retry mechanism
let attempts = 0;
let success = false;
do {
console.log("Attempt:", attempts + 1);
// Try operation
success = Math.random() > 0.7; // 30% success rate
attempts++;
} while (!success && attempts < 5);
if (success) {
console.log("Success after", attempts, "attempts");
} else {
console.log("Failed after", attempts, "attempts");
}
// Generate random until condition met
let randomNum;
let count = 0;
do {
randomNum = Math.floor(Math.random() * 10);
count++;
console.log("Generated:", randomNum);
} while (randomNum !== 7);
console.log("Found 7 after", count, "tries");Avoiding Infinite Loops
An infinite loop runs forever because its condition never becomes false. This crashes your program!
Common Infinite Loop Mistakes
// WRONG: Forgot to increment
// let i = 0;
// while (i < 5) {
// console.log(i);
// // i never changes! Infinite loop!
// }
// WRONG: Incrementing wrong direction
// let j = 0;
// while (j < 10) {
// console.log(j);
// j--; // Going backwards! Infinite loop!
// }
// WRONG: Condition always true
// let k = 0;
// while (k >= 0) {
// console.log(k);
// k++; // k is always >= 0! Infinite loop!
// }
// WRONG: Never updating condition variable
// let found = false;
// while (!found) {
// console.log("Searching...");
// // found never changes! Infinite loop!
// }
// RIGHT: Proper increment
let i = 0;
while (i < 5) {
console.log(i);
i++; // Changes in right direction
}
// RIGHT: Eventually becomes false
let found = false;
let attempts = 0;
while (!found && attempts < 10) {
console.log("Attempt:", attempts);
found = Math.random() > 0.8; // Might become true
attempts++; // Safety: stops after 10 tries
}Safety Patterns
// Pattern 1: Maximum iterations
let maxAttempts = 100;
let attempts = 0;
let result = null;
while (result === null && attempts < maxAttempts) {
// Try to get result
result = tryGetResult();
attempts++;
}
if (result) {
console.log("Success:", result);
} else {
console.log("Failed after", maxAttempts, "attempts");
}
// Pattern 2: Timeout
let startTime = Date.now();
let timeout = 5000; // 5 seconds
while (Date.now() - startTime < timeout) {
// Do work
if (checkIfDone()) {
break; // Exit when done
}
}
// Pattern 3: Break condition
while (true) {
let value = getNextValue();
if (value === null) {
break; // Exit when no more values
}
processValue(value);
}
// Pattern 4: External flag
let keepRunning = true;
let iteration = 0;
while (keepRunning) {
console.log("Running:", iteration);
iteration++;
if (iteration >= 10) {
keepRunning = false; // Stop condition
}
}How to stop an infinite loop:
- In browser: Close the tab
- In Node.js: Press Ctrl+C
- In VS Code: Click the stop button
Prevention: Always ensure your loop variable changes in a way that makes the condition false eventually!
Practical While Loop Patterns
Pattern 1: Input Validation
function getValidNumber(min, max) {
let num;
let isValid = false;
while (!isValid) {
// num = prompt(`Enter number between ${min} and ${max}:`);
num = 50; // Simulating input
num = Number(num);
if (!isNaN(num) && num >= min && num <= max) {
isValid = true;
} else {
console.log("Invalid! Try again.");
break; // For demo purposes
}
}
return num;
}
// let age = getValidNumber(0, 120);
// console.log("Valid age:", age);
// Email validation loop
function getValidEmail() {
let email;
let isValid = false;
while (!isValid) {
// email = prompt("Enter email:");
email = "user@example.com"; // Simulating input
if (email.includes("@") && email.includes(".")) {
isValid = true;
} else {
console.log("Invalid email format");
break; // For demo purposes
}
}
return email;
}
// let email = getValidEmail();
// console.log("Valid email:", email);Pattern 2: Processing Until Done
// Read data until end marker
function processData(data) {
let index = 0;
let results = [];
while (index < data.length && data[index] !== "END") {
results.push(data[index].toUpperCase());
index++;
}
return results;
}
let data = ["apple", "banana", "END", "orange"];
console.log(processData(data)); // ["APPLE", "BANANA"]
// Process queue until empty
function processQueue(queue) {
let processed = 0;
while (queue.length > 0) {
let item = queue.shift(); // Remove first item
console.log("Processing:", item);
processed++;
}
return processed;
}
let queue = ["task1", "task2", "task3"];
console.log("Processed:", processQueue(queue), "items");
// Search until found or exhausted
function findInArray(array, target) {
let index = 0;
let found = false;
while (index < array.length && !found) {
if (array[index] === target) {
found = true;
} else {
index++;
}
}
return found ? index : -1;
}
let numbers = [5, 10, 15, 20, 25];
console.log("Index of 15:", findInArray(numbers, 15)); // 2
console.log("Index of 99:", findInArray(numbers, 99)); // -1Pattern 3: Accumulation with Condition
// Sum numbers until threshold
function sumUntilThreshold(threshold) {
let sum = 0;
let num = 1;
let numbersUsed = [];
while (sum < threshold) {
sum += num;
numbersUsed.push(num);
num++;
}
return {
sum: sum,
count: numbersUsed.length,
numbers: numbersUsed
};
}
console.log(sumUntilThreshold(50));
// { sum: 55, count: 10, numbers: [1,2,3,4,5,6,7,8,9,10] }
// Build string until max length
function buildString(words, maxLength) {
let result = "";
let index = 0;
while (index < words.length && result.length < maxLength) {
let nextWord = words[index];
if (result.length + nextWord.length <= maxLength) {
result += (result ? " " : "") + nextWord;
index++;
} else {
break;
}
}
return result;
}
let words = ["The", "quick", "brown", "fox", "jumps"];
console.log(buildString(words, 15)); // "The quick brown"Pattern 4: Game Loop
// Simple number guessing game
function guessingGame() {
let target = Math.floor(Math.random() * 100) + 1;
let guesses = 0;
let maxGuesses = 10;
let won = false;
console.log("Guess the number between 1 and 100!");
while (guesses < maxGuesses && !won) {
guesses++;
// let guess = prompt(`Guess #${guesses}:`);
let guess = target; // Auto-win for demo
guess = Number(guess);
if (guess === target) {
won = true;
console.log(`You won in ${guesses} guesses!`);
} else if (guess < target) {
console.log("Too low!");
} else {
console.log("Too high!");
}
}
if (!won) {
console.log(`Game over! The number was ${target}`);
}
return { won, guesses };
}
// guessingGame();
// Coin flip game
function coinFlipGame(targetWins) {
let wins = 0;
let losses = 0;
let flips = 0;
while (wins < targetWins) {
flips++;
let result = Math.random() < 0.5 ? "heads" : "tails";
if (result === "heads") {
wins++;
console.log(`Flip ${flips}: Heads! (Wins: ${wins})`);
} else {
losses++;
console.log(`Flip ${flips}: Tails (Losses: ${losses})`);
}
}
return { wins, losses, flips };
}
console.log(coinFlipGame(3));Practical Examples
Example 1: Password Checker with Retry
function checkPassword(correctPassword, maxAttempts = 3) {
let attempts = 0;
let isAuthenticated = false;
do {
attempts++;
// let password = prompt(`Enter password (Attempt ${attempts}/${maxAttempts}):`);
let password = attempts === 2 ? correctPassword : "wrong";
if (password === correctPassword) {
isAuthenticated = true;
console.log("✓ Access granted!");
} else {
let remaining = maxAttempts - attempts;
if (remaining > 0) {
console.log(`✗ Wrong password. ${remaining} attempts remaining.`);
}
}
} while (!isAuthenticated && attempts < maxAttempts);
if (!isAuthenticated) {
console.log("✗ Account locked. Too many failed attempts.");
}
return {
authenticated: isAuthenticated,
attempts: attempts
};
}
console.log(checkPassword("secret123"));Example 2: Data Processor with Validation
function processOrders(orders) {
let index = 0;
let processed = [];
let failed = [];
while (index < orders.length) {
let order = orders[index];
// Validate order
if (!order.id || !order.total || order.total <= 0) {
failed.push({
order: order,
reason: "Invalid order data"
});
index++;
continue;
}
// Process valid order
let processedOrder = {
id: order.id,
total: order.total,
tax: order.total * 0.08,
finalTotal: order.total * 1.08,
status: "processed"
};
processed.push(processedOrder);
index++;
}
return {
processed: processed,
failed: failed,
summary: {
total: orders.length,
success: processed.length,
failed: failed.length
}
};
}
let orders = [
{ id: 1, total: 50 },
{ id: 2, total: -10 }, // Invalid
{ id: 3, total: 100 },
{ total: 75 } // Missing id
];
console.log(processOrders(orders));While and Do-While Practice
Experiment with condition-based loops
console.log() to see your output in the console above.Key Takeaways
- While loops check condition before execution
- Do-while loops check condition after execution (runs at least once)
- Use while when you don't know how many iterations needed
- Use do-while when you must execute at least once
- Always ensure loop variable changes to prevent infinite loops
- Add safety limits (max iterations, timeout) for protection
- While loops are perfect for validation and condition-based processing
- For loops are better when you know exact iteration count
- Use
breakto exit loops early when condition is met - Test your loop conditions carefully to avoid infinite loops
What's Next?
You now understand how to use while and do-while loops for condition-based iteration! These loops are essential when you don't know in advance how many times you need to repeat code.
In the next lesson, we'll explore For...of and For...in Loops—modern JavaScript loops designed specifically for iterating over arrays, strings, and object properties. They're cleaner and more intuitive than traditional for loops for many common tasks!
💪 Practice Challenge:
Before moving on, try creating:
- A function that keeps asking for input until it's valid (age between 0-120)
- A number guessing game using a while loop
- A function that processes an array until it finds a specific value
- A do-while loop that displays a menu until user chooses "exit"
- A function that simulates rolling dice until you get a 6