Spot the Missing Base Case
Find the Mistake Medium
Question
This recursive function causes a stack overflow. What is wrong?
Code
function sum(n) {
return n + sum(n - 1);
}
console.log(sum(5));
Hint
The function never stops calling itself.
Explanation
The function has no base case, so it calls itself forever: sum(5) → sum(4) → sum(3) → ... → sum(-infinity). Each call adds to the call stack until it overflows. The fix is to add a base case: if (n <= 0) return 0; at the beginning, so the recursion stops when n reaches 0.
Related Resources
Related Lessons
- Recursion
Learn about recursive functions.
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.