How to Understand Recursion in JavaScript?


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, it stops its execution of itself. Let’s understand what is the base condition by one example. For example, 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.

Syntax

Users can use the syntax below to understand the recursion in JavaScript.

function recur(val) {
   if (base condition) {
      return;
   }
   
   // perform some action
   
   // decrease the value of val by one step
   return recur(newVal);
}

In the above syntax, users can observe that we return null when the base condition becomes true to stop the execution of the function. If the base condition is false, we perform some action with the input value and call the recur() function again with a new parameter value.

Now, let’s look at the various examples of recursion. Here, we will learn to implement the iterative algorithm first using for loop and then convert it to the recursive approach.

Example 1 (Find the sum of 1 to n numbers using for loop)

In the example below, we have written the sumOfN() function to get the sum of 1 to N numbers. We have used the for loop to make N iterations, and in every iteration, we add the value of I to the sum variable.

At last, it returns the value of the sum variable.

<html>
<body>
   <h3>Using the <i> iterative approach </i> to find sum of n numbers in JavaScript</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      
      // function to find the sum of n numbers using an iterative approach
      function sumOfN(n) {
         let sum = 0;
         for (let i = n; i >= 1; i--) {
            sum += i;
         }
         return sum;
      }
      content.innerHTML += "The sum of 1 to 10 numbers is " + sumOfN(10) + "<br>";
      content.innerHTML += "The sum of 1 to 20 numbers is " + sumOfN(20) + "<br>";
   </script>
</body>
</html>

In the above example, we have used the iterative approach to find the sum of N numbers. Now, we will use the recursive approach to do the same.

Example 2 (Find the sum of 1 to n numbers using the recursive function)

The sumOfN() function is a recursive function in the example below. We repeatedly invoke the sumOfN() function by decreasing the parameter's value by 1. The sumOfN(N1) returns the sum of N-1 numbers, and we add N to it to get the sum of N numbers. Whenever the value of N becomes 1, it returns one, which works as a base condition to stop the execution of the function.

<html>
<body>
   <h3>Using the <i> recursive approach </i> to find sum of n numbers in JavaScript</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      
      // function to find the sum of n numbers using a recursive approach
      function sumOfN(n) {
         
         // base condition
         if (n == 1) {
            return 1;
         }
         
         // call function recursively by decreasing the value of n by 1.
         return n + sumOfN(n - 1);
      }
      content.innerHTML += "The sum of 1 to 10 numbers is " + sumOfN(10) + "<br>";
      content.innerHTML += "The sum of 1 to 20 numbers is " + sumOfN(20) + "<br>";
   </script>
</body>
</html>

Let’s understand how the above recursive function works. Below, users can understand how recursive function call occurs step by step.

sumOfN(5);
return 5 + sumOfN(4);
   return 4 + sumOfN(3);
      return 3 + sumOfN(2);
         return 2 + sumOfN(1);
            return 1;
         return 2 + 1;
      return 3 + 3;
   return 4 + 6; 

Example 3 (Iterative approach to merge all strings of the array)

In the example below, we have created the array of strings. We have created the mergeString() function to merge all strings of the array into a single string. We used the for loop to iterate through the array and merge all strings one by one to the ‘str’ variable.

<html>
<body>
   <h3>Using the <i> iterative approach </i> to merge all strings of the array in JavaScript</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      
      // function to merge all strings of the array using for loop
      function mergeString(arr) {
         let str = '';
         for (let i = 0; i < arr.length; i++) {
            str += arr[i];
         }
         return str;
      }
      let arr = ['I', ' ', 'am', ' ', 'a', ' ', 'programmer'];
      content.innerHTML += "The original array is: " + arr + "<br>";
      content.innerHTML += "After merging all strings of the array into the single string is " + mergeString(arr) + "<br>";
   </script>
</body>
</html>

Example 4 (Recursive approach to merge all strings of the array)

We have converted the mergeString() function to a recursive function in the example below. We get the first element of the array and merge it with the returned result from the mergeString() function. The mergeString() function returns the last n-1 array elements after merging. Also, we use the slice() method to remove the first element from the array.

When only one element is left in the array, it returns the same element, which works as a base condition.

<html>
<body>
   <h3>Using the <i> Recursive approach </i> to merge all strings of the array in JavaScript</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      
      // function to merge all strings of the array using recursion
      function mergeString(arr) {
         
         // based condition
         if (arr.length == 1) {
            return arr[0];
         }

         // remove the first element from the array using the slice() method.
         return arr[0] + " " + mergeString(arr.slice(1));
      }
      let arr = ["I", "am", "a", "web", "developer"];
      content.innerHTML += "The original array is: " + arr + "<br>";
      content.innerHTML += "After merging all strings of the array into the single string is " + mergeString(arr) + "<br>";
   </script>
</body>
</html>

Which approach should users use, iterative or recursive?

The main question is which approach is better, iterative or recursive and which approach users should use.

The iterative approach is faster than the recursive approach in some cases. Furthermore, recursion takes more memory over the iterations. For some algorithms like the divide and conquer approach, recursion is more useful as we need to write less code with the recursive approach. Also, users can face the memory leak problem if the base condition doesn’t trigger in the recursive approach.

If we can break down the code into smaller parts, we should use the recursive approach, and to improve the performance of the code, we should use the iterative approach.

Updated on: 09-Mar-2023

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements