Choosing While vs For
You'll learn: How to decide between while and for loops based on clarity and common JavaScript style.
Both while and for loops can accomplish the same tasks—they both repeat code until a condition becomes false. The question isn't can you use one, but rather which one makes your intent clearer.
When to Use For Loops
Use a for loop when you know how many times you'll iterate, especially when counting:
// Clear: counting from 0 to 9
for (let i = 0; i < 10; i++) {
console.log(i);
}
The for loop bundles initialization, condition, and increment in one line—perfect for "do this N times" or "iterate through indices."
When to Use While Loops
Use a while loop when repetition depends on a condition that isn't a simple counter:
let userInput = '';
// Keep asking until valid input
while (userInput !== 'yes' && userInput !== 'no') {
// (imagine getting input here)
userInput = getInput();
}
Here, you're not counting—you're repeating until something happens. A for loop would feel forced.
The Clarity Test
Think of for as "repeat this count" and while as "repeat while true." If you find yourself writing while (i < 10) and managing i++ inside the body, you probably want a for loop instead. Conversely, forcing a counting variable into a for loop when you're really waiting for a condition makes code harder to read.
Key Takeaway: Use for loops for counting and indexed iteration; use while loops when repetition depends on a changing condition unrelated to counting. Choose whichever makes your intent immediately obvious.