Recursion in JavaScript
Recursion is a programming technique where a function calls itself to solve a problem. Recursive functions are useful for tasks that can be broken down into smaller, similar sub-problems.
How Recursion Works
A recursive function usually has two main parts:
- Base Case: The condition that stops the recursion. Without it, the function would call itself indefinitely, causing a stack overflow error.
- Recursive Case: The part of the function where it calls itself with a smaller or simpler input.
General Syntax:
function recursiveFunction(params) {
if (baseCondition) {
return someValue; // Base case
}
return recursiveFunction(modifiedParams); // Recursive call
}
Example: Factorial Function
The factorial of a number n
(denoted as n!
) is calculated as:
n! = n × (n-1) × (n-2) × ... × 1
Recursive Implementation:
factorial(5)
callsfactorial(4)
factorial(4)
callsfactorial(3)
… untilfactorial(1)
function factorial(n) {
if (n === 0 || n === 1) { // Base case
return 1;
}
return n * factorial(n - 1); // Recursive call
}
console.log(factorial(5)); // Output: 120
Example: Fibonacci Series
The Fibonacci sequence is a series where each number is the sum of the previous two numbers.
fibonacci(6)
→fibonacci(5)
+fibonacci(4)
- Continues until base cases (
n <= 1
) are reached
function fibonacci(n) {
if (n <= 1) return n; // Base case
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive call
}
console.log(fibonacci(6)); // Output: 8
Advantages of Recursion
- Simplifies complex problems like tree traversal, graph algorithms, and divide-and-conquer solutions
- Makes code more readable and elegant in certain scenarios
Disadvantages of Recursion
- Can cause stack overflow if the recursion is too deep
- May be less efficient than iterative solutions due to multiple function calls
- Needs a well-defined base case to terminate correctly