Last Updated : 23 Jul, 2025
Recursion is a process in which a function calls itself as a subroutine. This allows the function to be repeated several times, as it can call itself during its execution. Recursion is often used to solve problems that can be broken down into smaller, similar subproblems.
Syntax: JavaScript
function recursiveFunction(parameters) {
// Base case: stopping condition
if (baseCase) {
return baseCaseValue;
}
// Recursive case: function calls itself
return recursiveFunction(modifiedParameters);
}
Key Components:Example : Factorial of a Number JavaScript
- Base Case:
- This is the condition that stops the recursion.
- Without a base case, the function will call itself indefinitely, leading to a stack overflow.
- Example: If calculating the factorial of a number, the base case is when the number is 0 or 1.
- Recursive Case:
- This is where the function calls itself with a modified input.
- The input is typically modified to move closer to the base case.
- Example: For factorial, the recursive case is n * factorial(n - 1).
function factorial(n) {
// Base case: if n is 0 or 1, return 1
if (n === 0 || n === 1) {
return 1;
}
// Recursive case: n! = n * (n-1)!
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120
Why Use Recursion?
Recursion is particularly useful for solving problems that can be divided into smaller, identical problems. Some common use cases include:
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones (e.g., 0, 1, 1, 2, 3, 5, 8, ...).
JavaScript
function fibonacci(n) {
// Base case: return n if n is 0 or 1
if (n === 0 || n === 1) {
return n;
}
// Recursive case: sum of the two preceding numbers
return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(6)); // Output: 8
Application of Recursion
Tail recursion is a special form of recursion where the recursive call is the last operation in the function. This means that the function doesn't perform any additional computation after the recursive call returns. Tail recursion is important because it can be optimized by the compiler or interpreter to avoid growing the call stack, making it more memory-efficient.
Key Characteristics of Tail RecursionWhen to Use Tail Recursion
- Use tail recursion when you need to solve a problem recursively and want to avoid stack overflow.
- Tail recursion is particularly useful for problems that involve large inputs or deep recursion.
function factorial(n, accumulator = 1) {
// Base case:
if (n === 0 || n === 1) {
return accumulator;
}
// Tail-recursive call:
return factorial(n - 1, n * accumulator);
}
console.log(factorial(5)); // Output: 120
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4