In JavaScript, when using recursive functions, you must return the value from both the base case and the recursive call to ensure the final result propagates back up the call stack. Here's how to do it correctly:
Key Principles:
- Base Case: Return a concrete value (stopping condition).
- Recursive Case: Return the result of the function's next call (with modified arguments).
- Propagation: Combine/return the recursive result with the current operation.
Example 1: Factorial Calculation
function factorial(n) {
// Base case: return 1 for n = 0 or 1
if (n <= 1) return 1;
// Recursive case: return n multiplied by factorial(n-1)
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
Example 2: Sum of an Array
function sumArray(arr, index = 0) {
// Base case: end of array
if (index === arr.length) return 0;
// Recursive case: current element + sum of the rest
return arr[index] + sumArray(arr, index + 1);
}
console.log(sumArray([1, 2, 3])); // 6
Common Mistake: Missing return
Incorrect (returns undefined):
function brokenFactorial(n) {
if (n <= 1) return 1;
n * brokenFactorial(n - 1); // ❌ Missing return!
}
console.log(brokenFactorial(5)); // undefined
Fix: Always use return before the recursive call.
How the Call Stack Works (Factorial Example):
factorial(3)
return 3 * factorial(2)
factorial(2) → return 2 * factorial(1)
factorial(1) → return 1 (base case)
// Unwinds: 2 * 1 = 2
// Unwinds: 3 * 2 = 6
Key Takeaways:
- Base Case: Must return a value without recursion.
- Recursive Case: Use
return to pass the result backward.
- Combine Results: Use operations (e.g.,
n * ..., arr[i] + ...) to merge the current step with the recursive result.
By following this pattern, values computed in deeper recursion levels correctly propagate to the initial call.