A Function That Calls Itself — Base Case + Recursive Case + Progress
Introduction to Recursion
Recursion is a technique where a function solves a problem by calling itself on a smaller version of the same problem until a base case ends the chain.
What you'll learn
- Define recursion and identify the base case and recursive case in any example
- Trace the call chain of a recursive factorial function step by step
- Apply the "trust the recursion" mental model to write recursive functions confidently
Recursion is one of those ideas that sounds circular — and that is exactly the point. A recursive function solves a problem by calling itself on a smaller version of the same problem, repeating until the problem becomes trivial enough to answer directly.
Every recursive solution has two parts:
- Base case — the condition where the function stops and returns a known answer without calling itself again.
- Recursive case — the part where the function calls itself with a smaller or simpler input, making progress toward the base case.
Factorial: The Classic First Example
The mathematical factorial of a non-negative integer n is the product of
every integer from 1 to n. The recursive definition is:
factorial(0) = 1(base case)factorial(n) = n * factorial(n - 1)(recursive case)
function factorial(n) {
// Base case: 0! is defined as 1
if (n === 0) return 1;
// Recursive case: n! = n * (n-1)!
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120 Tracing factorial(5):
5 * factorial(4)5 * 4 * factorial(3)5 * 4 * 3 * factorial(2)5 * 4 * 3 * 2 * factorial(1)5 * 4 * 3 * 2 * 1 * factorial(0)→ base case returns1- Products multiply back up:
120
Trust the Recursion
The hardest mental shift for beginners is resisting the urge to mentally trace every nested call. Instead, use the trust the recursion principle: assume your function already works correctly for any input smaller than the current one, then write just the current step in terms of that assumption.
For factorial: “Assume factorial(n-1) gives the right answer. Then
factorial(n) is simply n * factorial(n-1).” That assumption is justified
because eventually every call reaches the base case.
Progress Toward the Base Case
Every recursive call must move closer to the base case. If it does not,
calls accumulate indefinitely and the call stack overflows — you will see a
RangeError: Maximum call stack size exceeded in V8. For factorial, n
decreases by 1 each call, so it always reaches 0.
The three questions to ask when writing any recursive function:
- What is the base case and what does it return?
- How does the recursive call use a smaller input?
- How does the result of the recursive call combine to form the full answer?
Up Next
Now that you know what recursion is, see what actually happens in memory when functions call themselves — and why there is a hard limit on depth.
The Call Stack →