How does recursion function work in JavaScript?



This article will teach you how to create a JavaScript recursive function-a function that calls itself-using the recursion method. The process of recursion involves calling itself. Recursive functions are those that call themselves repeatedly. A condition to cease calling itself is always included in recursive functions. Otherwise, it will continue to call itself. Recursive functions are typically used to divide a large issue into smaller ones. Recursive functions are frequently found in data structures like binary trees, graphs, and algorithms like binary search and quick-sort.

A recursive function is not immediately clear or simple to comprehend. You will read and comprehend a recursive function more quickly if you understand the next statements. Before anything else, you should always determine the function's base case. Send parameters to the function so it can reach the basic case immediately. Decide which inputs will at least once invoke the recursive function.

Reading and writing recursive functions are nearly identical. Make a regular function that can be accessed via its parameters and has a base case. Provide parameters to the function so it may directly invoke the basic case. Pass the following parameters that start the recursive call.

Let's see different methods to see how recursion works in JavaScript.

Factorial of a number using Recursion

The factorial of a positive number n is given by −

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.

Syntax

Following is the syntax for a recursive function −

function recursion() {
   if(condition) {
      recursion();
   } else {
      // stop calling recursion()
   }
}
recursion();

Example

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>
<head>
   <title> Factorial using Recursion </title>
</head>
<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>

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

Cyclic Recursion

We shall observe in this technique how a certain function1(a) calls function2(b), function2(b) calls function3(c), and function3(c) calls function1(a), creating a cycle.

Example

In the below example, we have created three functions to understand this method. First, we create a function funA() with a variable named n. We check whether this value is less than 0 and perform a certain operation (n-1). This function calls funB(), which performs a certain operation (n-2) after checking whether n is greater than 2. Then funB() calls another function funC() which takes parameter (n). This is how nested recursion works.

<html>
<body>
   <h2> Nested Recursion using JavaScript </h2>
   <script>
      // JavaScript program to show Cyclic Recursion
      function funA(n) {
         if (n > 0) {
            document.write(n.toFixed(0) + "</br>");
            // Fun(A) is calling fun(B)
            funB(n - 1);
         }
      }
      function funB(n) {
         if (n > 1) {
            document.write(n.toFixed(0) + "</br>");
            // Fun(B) is calling fun(C)
            funC(n - 2);
         }
      }
      function funC(n) {
         if (n > 1) {
            document.write(n.toFixed(0) + "</br>");
            // Fun(C) is calling fun(A)
            funA(n);
         }
      }
      funA(5);
   </script>
</body>
</html>

Users can observe that the first value given to funA() is 5. Then performing (n-1) we get 4. Then (n-2) we get 2. Similarly, (n) we get 2. Then we get (n-1) is 1 given to funB().

Nested Recursion

The parameter will be sent as a recursive call in this recursion by a recursive function. "Recursion inside recursion" is what that implies. To comprehend this recursion, let's look at an example.

Syntax

func(n)
{
   Return func(func(n-1))
}

Parameter

  • n − Parameter used to perform any calculation in nested recursion.

Example

In this example, we create a function named fun() which gets a value of num from the driver program. Here we created a function nested that takes one integer parameter. Inside this function there is an if-else block, it checks if num> 100 then return num- 10 else return nested (nested (num + 11)).

<html>
<body>
   <h3> JavaScript program to show Nested Recursion </h3>
   <script>
      function fun(num){ 
         // A recursive function passing parameter
         // as a recursive call or recursion
         // inside the recursion
         if (num > 100)
            return (num - 10);
         else
            return fun(fun(num + 11));
      }
      var r;
      r = fun(98);
      document.write(r);
   </script>
</body>
</html>

The output shows how the 98 passed as num will be recursively called and will give a value of 91 in the end.

Conclusion

The three approaches shed light on different approaches to carrying out recursion. The first is a simple approach that helps the user to find out the factorial of a number. The second approach helps see how three functions can be used to perform recursion using the cyclic recursion technique. The third approach shows how nested recursion takes place in JavaScript.


Advertisements