JavaScript - Recursion



Recursion is a process in which a function calls itself. It helps when we need to solve a problem that can be break down into smaller problem of the same type.

What is Recursion?

The word recursion came from the recurring, meaning comes back to again and again. The recursion function is the function calling itself again and again by changing the input step by step. Here, changing the input by one step means decreasing or increasing the input by one step.

Whenever a recursive function hits the base condition, the execution stops. Let's understand what is the base condition by one example. Suppose, we need to find the factorial of a number. We call the factorial function by decreasing the input by 1, and we need to stop whenever the input reaches 1. So, here one works as a base condition.

How Recursion Works?

Recursion works on the concept of divide and conquer. It does means we divide the problem into smaller parts and solve them. The recursion function calls itself with the smaller input and solves the problem, and when the base condition is met recursion stops.

Example of Recursion

Let us understand how to write a recursive function to find the factorial of a number. The factorial of a positive number n is given as follows −

Factorial of n (n!) = 1 * 2 * 3 * 4 *... * n

The factorial of a negative number doesn't exist. And the factorial of 0 is 1

In the below example, we will demonstrate how to find the factorial of a number using recursion in JavaScript. We create a function fact() with a parameter b that takes a value from the main function as 6.

  • Firstly, we check if the number is equal to 0. If it is true then the program will return 1.
  • In the else-statement, we will check b*fact(b-1), which roughly translates to 6*(6-1).
  • In the next recursion, it will be 5*(5-1) and so on. In this way, the function will resume finding the factorial of a number.
  • The function then prints the value of the factorial of the number entered after the recursion ends.
<html>
<body>
   <h2> Factorial using JavaScript recursion </h2>
   <script>
      // program to find the factorial of a number
      function fact(b) {
         // if number is 0
         if (b === 0) {
            return 1;
         }
         // if number is positive
         else {
            return b * fact(b - 1);
         }
      }
      const n = 6;
      // calling factorial() if num is non-negative
      if (n > 0) {
         let res = fact(n);
         document.write(`The factorial of ${n} is ${res}`);
      }
   </script>
</body>
</html>

Output

The factorial of 6 is 720

In the above output, users can see that after recursion we find the factorial of the number to be 720.

Advertisements