Using Recursion as an Alternative for Loops

Using Recursion as an Alternative for Loops

I recently attended an interview for a Frontend Engineer Position and I completely blanked out during the live coding challenge because I didn’t know what concept to use to approach the problem. Well, if I had understood what I will be detailing in this article beforehand, the interview might have gone a different way. I am going to be solving the challenge using a basic JavaScript concept I learned recently- Recursion.

The Challenge

  • Recreate the native JavaScript setInterval function without using the function itself.

After the interviewer walked me through what I needed to do, I was given 30 minutes to solve the challenge, but I spent the first 15 minutes staying extremely confused as I thought of several approaches to use. I had two problems to tackle:

  1. How to appropriate delay in between a functions’ repeated executions.
  2. How to call the function persistently.

I thought of using a loop, but it was a bad idea as I made it infinite without solving the problem, leaving me to reset the page twice! To give a bit of a refresher on what the setInterval function does, it executes a function expression repeatedly at specified intervals. The repeated execution can only be terminated using a clearInterval function, which is also a native Javascript function.

The Syntax

setInterval(function, interval)

Parameters

  • function- code statements to be executed
  • interval- time in milliseconds (1000ms to 1s)

Demo Code

setInterval(function(){ console.log("Recursive!")}, 3000)

This code above will log to the console “Recursive!” every 3 seconds.

How The Challenge Can Be Solved

To solve the problems listed above:

1. Delay

The setTimeout function can be used to set a delay. The difference between the setInterval and setTimeout function is, while setInterval executes a function persistently in-between a specified interval,setTimeout executes a function only once after a specified time in milliseconds has elapsed. One can think of setTimeout as a delay setter.

The Syntax

setTimeout(function, timeout)

Parameters

  • function- code statements to be executed
  • timeout- time in milliseconds (1000ms to 1s)

Demo Code

function delayRecursive(){
       console.log(“Recursive!”)
}

 /*this will log Recursive! to the console only after 3 seconds.*/
setTimeout(delayRecursive, 3000)

2. Persistent Execution Calls

A common way of iterating statements is using a loop, nonetheless, there is a concept called Recursion in JavaScript that can be used to replace loops. A recursive function is a function expressed in terms of itself, this means the function calls itself during execution. Take a look at two versions of some code statements below.

They both add consecutive numbers from 1 to 3 and log the sum to the console. A condition is set to prevent an infinite addition of numbers in both cases. Observe the code carefully and see the explanation below it, describing what each line is doing.

For Loop

1   function add(n){
2
3     var sum = 0; 
4           
5      for(var i = 1; i <= n; i++){
6            sum += i;
7       }
8       
9      console.log(sum)        
10   }
11
12  add(3)

For Loop Explanation

      line 12:
      add(3) is called and executed

      line 3: initialize sum to 0
      sum = 0;

      line 5:
      run an iteration when (1 or 2 or 3) is less than or equal to 3

      line 6:
      sum = sum + i

      - first iteration 
      i = 1
      sum = 0 + 1 = 1;

      - second interation
      i = 2
      sum = 1 + 2 = 3;

      - third iteration
      i = 3
      sum = 3 + 3 = 6;

      line 9:
      logs the sum to the console = 6

Recursion

1    function sumRecursion(x, n){
2       if(x == n){
3           return x; 
4        }else{
5           return x + sumRecursion(x + 1, n)
6        }
7     }
8
9    console.log(sumRecursion(1, 3))

Recursion Explanation

   line 2:
   where x = 1 or 2 or 3
   if (1 or 2 or 3) is equal to 3, return the number 3 

   line 4:
   immediately starts its iteration
   the condition on line 2 is false on the first and second iteration

   - first iteration
   sumRecursion(1,3) returns the number 1
   x = 1, n = 3

   line 5:
   returns the sum of 1 and (sumRecursion((1 + 1), 3)- calls 
   itself with an increment of x)

   - second iteration
   sumRecursion(1 + 1, 3) returns the number 2
   x = 2, n = 3

   line 5:
   returns the sum of (1 + 2) + (sumRecursion((2 + 1), 3)) -calls 
   itself with an increment of x

   - third iteration
   sumRecursion(2 + 1, 3) returns the number 3
   x = 3, n = 3

   line 5:
   on line 2, the condition is true
   returns the sum of (1 + 2 + 3)

   line 9:
   logs the sum to the console = 6

Code Solution To The Challenge

The concept of recursion might seem a little hard to grasp at first, but once it starts to make sense, it becomes easy to apply its logic. Seeing how recursion works, the solution to the challenge is only less than six lines.

1      function loop(){
2         console.log("Recursive!")
3         setTimeout(loop,2000);
4       }
5      loop()

Explanation

      line 5: 
      loop() is called and executed

      line 2:
      "Recursive!" is displayed on the console the first time

      line 3:
      setTimeout() will delay for 2s, then call loop() again 

      line 2 displays "Recursive!" again, and the loop continues

The function calls itself and creates a loop. However, in this case, I did not set a condition, and as a result, the function will run infinitely. This instance should be put into consideration when programming with this kind of logic.

Conclusion

Recursion can enable a programmer to write cleaner and elegant code, however, there is also the possibility of causing a memory leak. Additionally, in situations where conditions are not written to handle certain use cases, it may cause an infinite loop and result in a crashed/unresponsive program. To read up more on recursion, check out JavaScript Info.

If you have any questions, please feel free to comment below 😊