while & do...while Loops
while loops repeat as long as a condition is true — use them when you don't know how many iterations you need. do...while always runs at least once, then checks the condition.
while vs do...while
- while (condition) { } — Checks condition FIRST, then runs. May run 0 times
- do { } while (condition) — Runs FIRST, then checks. Always runs at least once
- Use while — When iterations are unknown: reading input, waiting for condition
- Use do...while — When you need at least one execution: menu prompts, retry logic
- ⚠️ Infinite loops — If condition never becomes false, the loop runs forever. Always ensure an exit
while & do...while Code
// while — may run 0 times
let count = 0;
while (count < 5) {
console.log("Count:", count);
count++;
}
// do...while — always runs at least once
let num = 10;
do {
console.log("Number:", num);
num--;
} while (num > 10);
// Prints "Number: 10" once even though 10 > 10 is false
// Real use case: find first power of 2 > 1000
let power = 1;
while (power <= 1000) {
power *= 2;
}
console.log("First power of 2 > 1000:", power); // 1024
// Real use case: password validation concept
let attempts = 0;
const maxAttempts = 3;
let success = false;
while (attempts < maxAttempts && !success) {
attempts++;
// Simulate checking password
if (attempts === 2) success = true; // correct on 2nd try
console.log(`Attempt ${attempts}: ${success ? "✅" : "❌"}`);
}Tip
Tip
Always ensure your while loop condition will eventually become false. Include the update step (counter++, flag = true) inside the loop body. A missing update creates an infinite loop that freezes the browser.
map/filter return new arrays; sort/splice mutate the original
Common Mistake
Warning
Forgetting to update the loop variable inside while, creating an infinite loop: while (count < 10) { console.log(count); } — count never increases, so the condition is always true. Always increment/update inside the loop body.
Practice Task
Note
Build a coin flip simulator: (1) Use Math.random() > 0.5 for heads/tails. (2) Use a while loop to flip until you get 3 heads in a row. (3) Count total flips needed. (4) Run it multiple times to see different results.
Quick Quiz
Key Takeaways
- while loops repeat as long as a condition is true — use them when you don't know how many iterations you need.
- while (condition) { } — Checks condition FIRST, then runs. May run 0 times
- do { } while (condition) — Runs FIRST, then checks. Always runs at least once
- Use while — When iterations are unknown: reading input, waiting for condition