Infinite loops: why your program hangs and never finishes
The tab freezes, nothing prints, and the loop condition never becomes false.
What is an infinite loop?
An infinite loop is a loop whose exit condition never becomes true. The program does not crash and does not print an error — it simply stops making progress, which makes it one of the more disorienting bugs to hit for the first time.
Why it happens
Every loop needs its body to move something toward the exit condition. The failure is almost always that the variable in the condition is not the variable the body changes: the increment sits inside an if, a continue jumps over it, a string method's return value is discarded so the text never actually changes, or a condition is tested against a value nothing updates.
How to recognise it
- It hangs on some inputs and finishes on others — the working ones avoid the branch that fails to make progress.
- A while loop whose body contains continue.
- A condition on one variable while the body updates a different one.
- In Python, calling text.replace(...) or list.sort() without assigning the result.
Error guides caused by this pattern
All error guides →In-depth guides for common exceptions and runtime errors triggered by infinite loops, with working fixes and real-world examples:
How to fix it
Print the condition variable at the top of every iteration. If it does not change, you have found it. Ask what happens when the branch is false: if the answer is 'nothing', the loop can stall. Put the increment where it always runs — a for loop's header is safer than a while loop's body.
Breaks vs Works Example
Breaks
// JavaScript: loop condition variable never advances
while (i < items.length) {
if (items[i] === target) break;
// forgetting i++ when target not matched hangs the tab
}Works
// JavaScript: increment is placed where it runs on every iteration
while (i < items.length) {
if (items[i] === target) break;
i++;
}💡 Always verify that every code path inside the loop moves state toward the exit condition.
Practise infinite loops
Working code with one bug in it. Find it, fix it in the browser, and see the explanation. No account needed.
Stuck on your own code?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.