Spot the Infinite Loop
Find the MistakeEasy
Question
This while loop is supposed to count down from 3 to 1, but it runs forever. What is wrong?
Code
let n = 3;
while (n > 0) {
console.log(n);
n = n + 1;
}
Hint
Look at how n changes inside the loop.
Explanation
The loop condition is n > 0, but inside the loop n is incremented (n = n + 1) instead of decremented. So n grows: 3, 4, 5, 6, ... and the condition n > 0 is always true. This creates an infinite loop. To count down, the update should be n = n - 1 (or n--).
Related Resources
Related Lessons
- Loops
Learn about JavaScript loop pitfalls.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.