Course contentsShow
← JavaScript
Lesson 339 of 2,72310. LoopsFree lesson

Avoiding Infinite Loops in While

Learn common mistakes that cause infinite loops and how to ensure your condition eventually becomes false.

Avoiding Infinite Loops in While

You'll learn how to prevent your while loops from running forever by ensuring your condition eventually becomes false.

The Danger of Infinite Loops

An infinite loop occurs when your while condition never becomes false. The loop keeps executing indefinitely, freezing your program and consuming resources until the browser tab crashes or you forcefully stop execution.

The most common cause? Forgetting to modify the variable that the condition checks.

The Classic Mistake

let count = 0;
while (count < 5) {
  console.log(count);
  // Oops! We never change count
  // This will print 0 forever
}

This loop checks if count < 5, but since count stays 0, the condition is always true. The loop never exits.

The Fix: Progress Toward Termination

Every while loop needs something inside its body that moves toward making the condition false:

let count = 0;
while (count < 5) {
  console.log(count);
  count++; // Now count changes and eventually reaches 5
}

Think of it like walking toward a destination: if you never take a step, you'll never arrive.

Another Common Trap

let i = 10;
while (i > 0) {
  console.log(i);
  i++; // Wrong direction! i gets bigger, not smaller
}

Here i starts at 10 and keeps increasing, so i > 0 remains true forever. You're walking away from your destination.

Checklist to Avoid Infinite Loops

  1. Identify the loop variable — which variable controls the condition?
  2. Modify it inside the loop — change that variable every iteration
  3. Move in the right direction — make sure changes bring you closer to false

Key Takeaway: Every while loop must modify the variable in its condition, moving it toward the point where the condition becomes false, or it will run forever.