Recursive Functions In JavaScript
Tags: javascript, typescript, node
Published: 2022-07-13 10:39:16

Recursion, doing something over and over and over and over and over and over again, recursion is an approach of solving a big problem by solving small parts of the problem repeatedly. Recursion in software development is often expressed as a function that calls back into itself. When we declare a recursive function, we have to make a call to that function we are declaring inside of it. 

Recursion is often used to tackle problems that are of a tree like nature or problems that implement a Merkel tree structure, where the sum total of the solution to a big problem is the cumulative result of solutions to the smaller problems. You should keep it my mind that  any problem that you can solve using a recursive function will always have an alternative looping solution. So a recursive function might not always be the best solution for every use case.

In this article we are going to look at how to create recursive functions, how to use recursive functions and how to identify solutions that meet this case, we'd also look at the benefits and tradeoffs that comes with implementing a recursive function.

## Declaring a recursive function

As we discussed above, we only need to declare a function that calls back into itself.

```javascript
function doSomething(){
  // call doSomething again
  doSomething();
}
```
We have a bare minimum of an implementation of a recursive function, we declare a function `doSomething` and inside of it we call `doSomething` again. If you are quite experienced writing code, you'd know that the function we have defined above will cause the JavaScript runtime to throw a  `stack overflow` error. 

This is because we push so many frames unto the stack by calling back to this function, each time the function is called, a new frame of that function is pushed on to the stack, and this goes on and on until we have exceeded the maximum amount of function frames that we can push onto the stack, and this is what causes the stack overflow error to be thrown.

We could negate this by adding a condition that will cause us to return from the function entirely, ending the recursion.

```javascript
function doSomething(){
  // exit condition
  if (condition) {
   return
  }
  // call doSomething again
  doSomething();
}
```
A more practical use case of a recursive function could be a function that finds the even numbers in a given number range. We would have a start argument and an end argument which are integers, inside the function we could check if we are at the end argument and if true we could use the return statement to exit out of the function, if not we could simply call the function again for the next integers while increasing it by 1.

```javascript
function findSquare(start, end) {
  if (start > end) {
    return;
  } else if (start % 2 == 0) {
     console.log(start);
  }
   findSquare(start++, end)
}

findSquare(0, 8);
// 0
// 2
// 4
// 6
// 8
```
Another example of a recursive function could be a function that counts down from a particular number which we could pass in as argument, we would make a recursive call to the function each time decreasing the value of the number until we get to 0.

```javascript
function countDown(start) {
  if (start <= 0) {
    return;
  } else {
    console.log(start);
    countDown(start--);
  }
}

countDown(2);

// 2
// 1
// 0
```
You might begin to wonder, this looks a lot like loops, and yes recursive functions are quite similar to loops but there is a difference between them.

### Difference between Recursions And Loops

* Like we established earlier, a recursive function will push a new function frame to the stack multiple times, however a loop will not push a function frame to the stack except we explicitly call a function inside the loop.

* There are only so much function frames that we can push onto the stack and if we exceed the limit, a stack overflow error will be thrown, thus there might be some cases where a recursive function will cause this to happen because of the sub problems we are trying to solve are just too much for the CPU to handle. A loop will not throw a stack overflow error, even if it is an endless loop, it will just keep on running and using all available CPU resources unless shutdown.

* Recursive functions also takes up more time than a loop and it is not as straight forward to find the amount of time consumed by each individual function execution since it might not be linear, however the time taken for a loop to execute can be found by getting the number of cycles being iterated inside the loop.

* Recursions can be quite complex to implement and understand properly since they involve functions, this also mean that there are shorter lines of code when using and working with recursive functions. Loops on the other hand are quite simple to implement and understand, it is just a block of code however loops could take up considerable longer line of code when compared to recursive functions.

### Pros of recursive functions

* Recursive functions are generally shorter and quite easy to debug especially if you understand how they work, being shorter and easier to debug leans it in the direction of being easier to maintain.

* A recursive function is very suitable to a problem that has a treelike structure.

* They are more suitable to a small set of problems, due to their elegant syntax.

### Con of using recursive functions

* A recursive function could potentially cause a stack overflow error to be thrown if we exceed the maximum amount of function frames that can be pushed to stack.

* Recursive function are generally slow depending on the logic implemented inside the code, repeatedly calling the function could lead to a potentially longer time.

### Should we use them?

There might be some use cases where working with recursive functions makes more sense and accurately handles the problem due to the nature of the problem, you should also keep in mind the drawback that comes with using recursive functions.

Personally i prefer using loops because I like keeping things simple and straight forward. Although there are some cases that I might encounter that would need a recursive function because i don't want to go through multiple files and finding every loop i implemented and then updating it. 

I like to consider the very likely problem of a stack overflow error happening in a live application and will only ever use a recursive function where it makes absolute sense.

Please leave your thoughts about recursion and recursive functions in the comment section down below, if there is something that you know about using recursive functions, feel free to drop it down below, you could also leave your thoughts and experiences with using recursive functions, that's it for this one, I hope you found it useful and you learnt something new from this and until next time.