Unit 5 · Data and algorithms
Recursion base case: why it never stops
A recursive function stops only when it reaches a base case you wrote, such as if (n === 0) return 0. Without one, it keeps calling itself until the computer runs out of room and throws “Maximum call stack size exceeded”.
The mix-up
What people often think
“The function will stop by itself when it runs out of numbers.”
What the tutor says
Nothing stops it unless you say when. Without a base case it opens box after box until the computer runs out of room.
What should countdown do when n reaches 0?
How it works
The recursive call is what continues the work, not what stops it. Each call must work on a smaller problem, like n - 1, so it gets closer to the base case. Calling again with the same n never arrives.
Check the base case first, before the recursive call. Code after a return never runs, so a base case at the bottom is never reached.
Side by side
function sumTo(n) {
return n + sumTo(n - 1); // never stops
}function sumTo(n) {
if (n === 0) return 0; // base case first
return n + sumTo(n - 1); // smaller each time
}Close cousins of this mix-up
The tutor watches for these in the same lesson.
“The recursive call is enough by itself.”
Without a base case, sumTo calls itself forever and the preview reports "Maximum call stack size exceeded". Add: if (n === 0) return 0.
“Calling the function again with n is fine.”
Each call must work on a smaller problem, or it never reaches the base case. Pass n - 1.
“The recursive call is what makes it stop.”
The call is what continues it. n - 1 moves it closer to the end, but only the base case actually stops it.
“The base case can go anywhere in the function.”
Code after a return never runs. Check the base case first, before the recursive call.
Practise it with a tutor watching
Recursion, lightly
Write a function that calls itself on a smaller problem and stops at a base case.
Free, no account needed.