What is Recursion In JavaScript? How Is It Works With Examples GBOB

What is Recursion In JavaScript? How Is It Works With Examples GBOB

What is Recursion?

Recursion is a programming concept where a function calls itself within its own body. This self-referential approach enables the function to solve complex problems by breaking them down into smaller, more manageable subproblems. Each recursive call operates on a smaller subset of data until a base case is reached, at which point the function starts returning results back up the call stack.

How Recursion Works in JavaScript

Base Case: Every recursive function must have a base case, which defines the condition under which the function stops calling itself and returns a value. Without a base case, the recursion would continue indefinitely, leading to a stack overflow error.

Recursive Call

In addition to the base case, the recursive function includes a call to itself, passing modified or smaller input parameters. This repetition allows the function to solve the problem iteratively, building upon previous iterations.

Stack Execution

When a function calls itself, the JavaScript engine creates a new execution context and adds it to the call stack. Each execution context keeps track of the function’s local variables and parameters. As the function reaches its base case, the execution contexts are removed from the stack in a last-in, first-out manner.

Example 1: Factorial Calculation

Let’s demonstrate recursion using the classic example of calculating the factorial of a number. The factorial of a non-negative whole number, represented as n!, is the result obtained by multiplying together all the positive integers that are smaller than or equal to n.

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

console.log(factorial(5)); // Output: 120

In this example, the factorial function calls itself with n – 1 until the base case (n === 0) is reached. The multiplication of n with the result of the recursive call ensures that the factorial is calculated correctly.

Example 2: Fibonacci Sequence

Another classic use case for recursion is computing the Fibonacci sequence, where each number is the sum of the two preceding ones.

function fibonacci(n) {
  if (n <= 1) {
    return n;
  }
  
  return fibonacci(n - 1) + fibonacci(n - 2);
}

console.log(fibonacci(6)); // Output: 8

In this example, the fibonacci function calls itself twice to compute the sum of the previous two numbers in the sequence. As with the factorial example, the recursion stops when reaching the base case (n <= 1).

Example 3: Function Factorial

function factorial(n) {
  // Base case: factorial of 0 or 1 is 1
  if (n === 0 || n === 1) {
    return 1;
  }
  
  // Recursive case: multiply n with factorial(n-1)
  return n * factorial(n - 1);
}

// Calculate the factorial of 5
console.log(factorial(5)); // Output: 120

Conclusion

Recursion is a powerful technique in JavaScript that allows functions to solve complex problems by breaking them down into smaller subproblems. By understanding the base case and recursive call, you can harness the full potential of recursion. Remember to always define a proper base case to prevent infinite recursion. As you gain familiarity with recursion, you’ll find it to be a valuable tool in your programming arsenal.

To dive deeper into JavaScript concepts, be sure to check out our article on <a href=”[link-to-article]”>Understanding Higher-Order Functions in JavaScript</a>. Happy coding!