Recursion in JavaScript

Recursion in JavaScript

Calls itself? Base condition? Alternative to loops?? Let's learn more about it!

·

4 min read

Recursion is the concept that a function can call itself with no end in sight until it has a condition (base case) that stops it from no longer doing so.

It can be useful when we need to split a task into several 'mini-tasks' that turn into more 'mini-tasks', or when we're dealing with certain data structures.

Think of it as a function that yells into an abyss with echo that comes back to it until it's done.

Recursion

Let's see the syntax of how recursive functions call themselves from the inside:

function recursiveCalling(){
 /// your code
 recursiveCalling()
/// more code
}
recursiveCalling()

But hold on! We need a base case for the function to stop calling itself or else... well, trust me when i say it's not pretty. It'll call itself indefinitely.

So, what's a base case?

A base case is a condition that once fulfilled tells the function it's time to rest and stop doing the recursion. We can use If... else where we place the recursive call in one and the base case in the other.

Let's see it:

function recursiveCalling(){
  if(prettyCoolCondition) {
   Stop doing it! 🤨
   } else {
    recursiveCalling() 😄
  }
}

Replacing loops with Recursion

Recursions are an alternative to using loops. Let's see how we can go from a loop to Recursion.

Let's see this for loop:

function factorialFun(n){
  var product = 1
  for(var i=n; i>=1; i--){
    product = product * i
  }
  return product
}

//factorialFun(8) -> 40,320

Now, let's make it recursive making it call itself from inside the function:

function factorialFunSize(n) {
  if (n<=1) { //our condition
  return 1
  } else {
    return n* factorialFunSize(n-1) //calling itself
  }
}

//factorialFunSize(8) -> 40,320

What is it doing?

It's calling itself but each time passing a minor value (decreasing the number) until it reaches the last one that gets 1 as a value, and it stops. So when it reaches the point where its calling itself it multiplies the returned values for n untill it reaches the top again and returns the value we're looking for.

So, the recursion reduces a function to a simpler one, and continues until the result becomes obvious, in our case is the response to (n<=1).

To calculate factorialFunSize(8):

  • Our function is n* factorialFunSize(n-1)

And the recursive did:

  • 8 * factorialFunSize (7-1)
  • 8 * factorialFunSize (6-1)
  • 8 * factorialFunSize (5-1)
  • 8 * factorialFunSize (4-1)
  • 8 * factorialFunSize (3-1)
  • 8 * factorialFunSize (2-1)
  • 8 * factorialFunSize (1-1) -> Will return 1 because of our condition and stop.

And then:

  • 8 * factorialFunSize (7-1) -> 56
  • 8 * factorialFunSize (6-1) -> 336
  • 8 * factorialFunSize (5-1) -> 1,680
  • 8 * factorialFunSize (4-1) -> 6,720
  • 8 * factorialFunSize (3-1) -> 20,160
  • 8 * factorialFunSize (2-1) -> 40,320
  • 8 * factorialFunSize (1-1) -> 40,320

Conclusion

Recursion is definitely one of those topics you need to go back to at least a couple of times. It has many benefits specially working with certain data structures like binary trees and many algorithms can also be written using recursion.

But you need to be careful when implementing it because since it keeps calling itself over and over again it needs greater space requirements than an iteration would, specially when working with large amounts of data. Don't let that discourage you, it's nothing you should be worrying about when working on personal projects.

💃 Fun fact! If you Google recursion it asks you: Did you mean recursion -wink wink-. Over and over, just like recursion does.

I really hope you learned something new today!

Thank you for reading!! :)

Don't hesitate to contact me and let me know if you'd like to add something else in the comments.

☕If you enjoy my content Buy me a coffee It'll help me continue making quality blogs💕

💙Follow me on Twitter to know more about my self-taught journey!

💜Make sure to check out more articles on my JavaScript For Newbies Series

❤️Also subscribe to my Youtube Channel !

🖤And for more content and tips on TikTok !

Resources