What happens if a recursive function has no base case?
It keeps calling itself, each call adds a frame to the call stack, and eventually the stack runs out of space. JavaScript throws a RangeError: Maximum call stack size exceeded.
Explain it simply
Recursion is like looking up a word in a dictionary, where the meaning sends you to another word, which sends you to another. If no word ever gives a plain answer, you keep flipping pages forever.
The base case is the plain answer that stops the chain. Every recursive call must move closer to it. Each unfinished call waits in memory as a frame on the call stack, so an endless chain fills the stack and the program crashes.
Example
function countDown(n) {
// missing: if (n === 0) return;
console.log(n);
countDown(n - 1);
}
try {
countDown(3);
} catch (e) {
console.log(e instanceof RangeError); // true, after the stack overflows
}
function fixed(n) {
if (n === 0) return 0; // base case
return n + fixed(n - 1);
}
console.log(fixed(4)); // 10What to say in the interview
"Without a base case, or with calls that never move toward it, recursion never stops. Each call occupies a stack frame, so the call stack overflows and JavaScript throws a RangeError. A correct recursive function has a base case and a recursive step that makes the problem smaller."
Common mistakes
- Writing a base case that the input can skip, for example checking n === 0 but passing n - 2 from an odd start.
- Forgetting to return the recursive call, so the result is undefined.