Recursion in JavaScript

Recursion in JavaScript

In JavaScript, recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result. It can be a useful alternative to using loops for certain tasks, especially when the number of iterations is not known in advance.

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

function factorial(n) {
    //base case
  if (n === 1) {
    return 1;
  }
  //recursive call
  return n * factorial(n - 1);
}

console.log(factorial(4)); // Output: 24

This function uses a base case of n === 1, which is when the function returns a result without making any more recursive calls. For all other values of n, the function calls itself with a modified argument (n - 1) and returns the result of the recursive call multiplied by n.

Recursion can be a powerful tool, but it's important to make sure that the base case is properly defined, or the function will enter an infinite loop. It can also be less efficient than using a loop, as each recursive call requires the creation of a new stack frame in memory.