While Loops: Repeat Until Done

While Loops: Repeat Until Done in JavaScript: A for loop is for when you know the count ("do this 10 times").

Concept Explanation

A for loop is for when you know the count ("do this 10 times"). A while loop is for when you don't — you repeat until a condition changes. Analogy: "keep scooping water until the bucket is empty." You don't know how many scoops it takes; you just stop when the bucket is empty.

The loop checks its condition before each run. The moment that condition is false, the loop ends and the program moves on.


Syntax or Core Structure

while vs. do...while

// while: checks FIRST, so it may run zero times
let lives = 3;
while (lives > 0) {
  console.log(`Lives left: ${lives}`);
  lives--;
}

// do...while: runs ONCE, then checks
let answer;
do {
  answer = prompt("Type 'yes' to continue");
} while (answer !== "yes");

Use do...while when the body must run at least once — like asking a question you have to ask before you can check the reply.


Real World Example

Retrying a flaky network request: "keep trying to reach the server while attempts are under 5 and we still have no data." You can't know in advance how many tries it takes, so a while loop fits perfectly — it stops the instant the request succeeds.


Common Mistakes

  1. The Infinite Loop: If nothing inside the loop changes the condition (you forgot lives--), it runs forever and freezes the tab. Always move toward the exit.
  2. Wrong loop for the job: When you know the exact count, a for loop is clearer than a hand-managed while counter.
  3. Off-by-one: while (i <= arr.length) reads one step past the end. Array positions stop at length - 1.

Best Practices

  • Guarantee progress: Every path through the loop should push the condition closer to false.
  • Add a safety valve: For risky loops, add if (++guard > 10000) break; so a bug can't hang the browser.
  • Name your condition: while (!isComplete) reads better than a cryptic math check.

Practice Exercises

  1. The Bank: Start with a balance of 100. Using a while loop, subtract 15 each round and print the balance until it drops below zero.
  2. The Dice: Use do...while to "roll" Math.random() until you get a value above 0.9, counting the rolls.
  3. The Digits: Given a number like 4823, use a while loop to add up its digits (4 + 8 + 2 + 3).