JavaScript Recursion
Recursion is a programming concept where a function calls itself to resolve the problem.
This is a simple term.
The syntax for the recursive function is:
function recursion() {
recursion();
}
recursion();
To must remember; recursive function to be called with base condition otherwise it will go to infinite loop and you will not be able to see the result.
It behaves anonymously.
That means A recursive function must have the condition to meet the result.
we can use if..else statement where once branch called similar function and other don’t to prevent the recursion.
so, generally it looks like
function(recursion) {
if(condition) {
recursion();
} else {
//stop calling recursion
};
}
recursion();
Another example of Recursion is to find the factorial.
Remember, in maths we studied what is factorial ?
example : 5!=5×4×3×2×1=120.
In general, for a non-negative integer n, the factorial n! is the product of all positive integers less than or equal to n:
n!=n×(n−1)×(n−2)×…×2×1.
It’s important to note that by convention, the factorial of 0 is defined to be 1 (0!=10!=1).
// Example: Calculating the factorial of a number using recursion
function factorial(n) {
// Base case: factorial of 0 or 1 is 1
if (n === 0 || n === 1) {
return 1;
} else {
// Recursive case: n! = n * (n-1)!
return n * factorial(n - 1);
}
}
// Testing the factorial function
console.log(factorial(5)); // Output: 120
In this example, the factorial
function calculates the factorial of a number using recursion.
The base case checks if the input n
is 0 or 1, in which case the function returns 1.
Otherwise, it recursively calls itself with the argument (n - 1)
until the base case is reached.
Here’s a step-by-step breakdown of how factorial(5)
is calculated:
factorial(5)
callsfactorial(4)
factorial(4)
callsfactorial(3)
factorial(3)
callsfactorial(2)
factorial(2)
callsfactorial(1)
factorial(1)
returns 1 (base case)factorial(2)
returns2 * 1
(result of2 * factorial(1)
)factorial(3)
returns3 * 2
(result of3 * factorial(2)
)factorial(4)
returns4 * 6
(result of4 * factorial(3)
)factorial(5)
returns5 * 24
(result of5 * factorial(4)
), which is 120.
This is a simple example, but it illustrates the basic idea of recursion. When using recursion, it’s crucial to have a base case to prevent infinite recursion and ensure that the function eventually terminates.