**Recursion** is a pattern where a function calls itself. Every recursive function needs a **base case** (the stopping condition) and a **recursive case** (the call that moves toward the base case). Without a base case, recursion causes a **stack overflow**.
1Understanding Recursive Functions
Recursion is a pattern where a function calls itself. Every recursive function needs a base case (the stopping condition) and a recursive case (the call that moves toward the base case). Without a base case, recursion causes a stack overflow.
JavaScript's call stack has a limit (~10,000 frames). For very deep recursion, use tail call optimization or an iterative approach.
// Classic factorial
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
console.log(factorial(5)); // 120
console.log(factorial(10)); // 36288002Practical Example
Here is a real-world application of Recursive Functions showing how it is used in production JavaScript code.
// Fibonacci with memoization
const memo = {};
function fib(n) {
if (n <= 1) return n;
if (memo[n]) return memo[n];
memo[n] = fib(n - 1) + fib(n - 2);
return memo[n];
}
console.log(fib(10)); // 55
console.log(fib(40)); // 102334155 (fast with memo)3Best Practices
Follow these guidelines when working with Recursive Functions:
1. Always define a clear base case first
2. Ensure each recursive call gets closer to the base case
3. Consider memoization for recursive functions with repeated sub-problems
Tip: JavaScript's call stack has a limit (~10,000 frames). For very deep recursion, use tail call optimization or an iterative approach.
// Classic factorial
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
console.log(factorial(5)); // 120
console.log(factorial(10)); // 3628800