Skip to content

Infinite Loop

Quick summary

Your loop never stops — the condition that should end it is always true or the loop variable never changes.

Why this happens

  • Forgot to update the loop variable inside the loop body

  • The exit condition can never become false

  • The increment or decrement step is missing or wrong

Minimal example

✗ Broken code
let i = 0;
while (i < 10) {
  console.log("hi");
}
✓ Fixed code
let i = 0;
while (i < 10) {
  console.log("hi");
  i++;
}

i is never incremented, so i < 10 is always true — adding i++ makes the loop terminate after 10 iterations.

How to diagnose

  • Check the loop condition — can it ever become false?

  • Verify the loop variable is modified inside the loop

  • Add a counter with a hard limit to catch the loop during debugging

How to fix

  • Ensure the loop variable changes each iteration toward the exit condition

  • Fix the exit condition so it can actually be reached

  • Add a safety break with a maximum iteration count

How to prevent

  • Prefer for loops over while loops when the iteration count is known

  • Always verify that the loop makes progress toward termination

Related Resources

Related Glossary

Related Lessons

  • Loops

    Learn how loops work in programming

Related Practice

← Back to language