- Recursion in JavaScript is a technique used to solve problems by breaking them down into smaller, more manageable sub-problems. In a recursive function, the function calls itself repeatedly until it reaches a base case, which is a problem that can be solved without further recursion.
- A recursive function consists of two parts: the base case and the recursive case. The base case is the condition under which the function stops calling itself and returns a value. The recursive case is the condition under which the function calls itself with a smaller input.
Here is an example of a recursive function that calculates the factorial of a number:
function factorial(n) {
if (n === 0) { // base case
return 1;
} else { // recursive case
return n * factorial(n - 1);
}
}
console.log(factorial(5)); // Output: 120
- In this example, the factorial function takes an input n and calculates its factorial by calling itself recursively with a smaller input. The base case occurs when n equals 0, at which point the function returns 1. The recursive case occurs when n is greater than 0, at which point the function multiplies n by the factorial of n - 1 and returns the result.
- Recursion can be a powerful tool for solving complex problems in JavaScript, but it can also be a source of bugs and performance issues if not used carefully. It's important to understand the concept of recursion and its limitations before using it in your code.
No comments:
Post a Comment