JavaScript(JS) Recursion

w‮figi.ww‬tidea.com

Recursion is a technique in programming where a function calls itself in order to solve a problem. In JavaScript, recursion can be used to solve problems that can be broken down into smaller sub-problems, such as tree traversal or searching through a nested data structure.

Here's an example of a recursive function in JavaScript that calculates the factorial of a number:

function factorial(n) {
  if (n === 0) {
    return 1;
  } else {
    return n * factorial(n - 1);
  }
}

In this example, the factorial function takes a number n as its argument and returns the factorial of n. If n is equal to 0, the function returns 1 (the base case). Otherwise, the function calls itself with n - 1 as the argument, and multiplies the result by n.

Here's how the factorial function works for n = 5:

factorial(5)
5 * factorial(4)
5 * 4 * factorial(3)
5 * 4 * 3 * factorial(2)
5 * 4 * 3 * 2 * factorial(1)
5 * 4 * 3 * 2 * 1
120

The factorial function calls itself recursively 4 times, each time with a smaller value of n, until it reaches the base case (when n is equal to 0) and returns 1. Then the function returns the product of all the recursive calls, which gives us the factorial of n.

Recursion can be a powerful tool in solving complex problems, but it's important to use it carefully, as it can lead to stack overflow errors if not implemented correctly. In some cases, an iterative solution may be more appropriate.