Recursion and tail recursion with JavaScript
Tags: javascript, recursion, codenewbie, tutorial
Published: 2020-10-22 10:04:22


Recursion is one of the topics that everyone covers, no matter which programming language you are learning. Probably in the first few classes of any beginner courses. Still, many people struggle with understanding it. This post covers what recursion is, what to watch for when writing a recursive function. Also, there is a section on a tail recursion, a bit more optimized version of recursion.

![JavaScript logo](https://dev-to-uploads.s3.amazonaws.com/i/6htlxbq0p3pag9ce4h6w.jpeg)
 
## What is recursion?
A commonly used definition of recursion is that it is a self-invoking function. But what does that mean? Usually, you write the function, and then you call it. With recursion, inside of the body of the function, you also call it.

```js
function recursiveFunction() {
    // some code
    recursiveFunction();
}
```

Looking at snippet about, you might think, this is an infinite loop. What about stack overflow? And you are right. When writing recursion, you need to pay special attention to the end case. But there is a bit more about that one bellow. First, answer to the other question you might ask. 


## Why and when would you use recursion? 
There are different use cases, and everyone has their own opinion. I think they are great when you need to loop something, but you don’t know how many times. Long pull from the server, where you are fetching data as long as there is some. Also, traversing the tree, like HTML nodes and nodes of binary trees. 

## Breaking recursion
As mentioned above, the end case always needs to be covered. That is the moment when you are stopping recursion. Otherwise, you get an infinite loop. Just for an example, let’s say we need to calculate the factorial of a number. If you don’t know what factorial is, there is a straightforward explanation on the [Wikipedia page](https://en.wikipedia.org/wiki/Factorial). Also, for simplicity, let’s assume the argument is always valid value.

```js
function factorial(number) {
    if(number === 1) {
        return number;
    } else {
        return number * factorial(number - 1);
    }
}

factorial(5); // 120
```

To calculate factorial, you sum all numbers until you reach one. That is also the end case for our recursion, and it is why once we reach value one, we don’t call factorial function anymore.

## Tail recursion
Tail recursion is a type of recursive function when the last thing executed is a recursive call. It doesn’t mean much, I know. But simplified, it is a more optimized recursion. So to explain it better, I am going back to the example above. That one is not tail recursion, and it executes in the following way.

```js
factorial(5); // step 1
5 * factorial(4); // step 2
5 * 4 * factorial(3); // step 3
5 * 4 * 3 * factorial(2); // step 4
5 * 4 * 3 * 2 * factorial(1); // step 5
5 * 4 * 3 * 2 * 1; // step 6
```

As you can see above, first, each factorial call is run. Only then it is multiplying all the number. To convert it to tail recursion, I am changing the function to accept the result as a second parameter.

```js
function tailRecursiveFactorial(number, result = 1) {
    if(number === 1) {
        return result;
    } else {
        return tailRecursiveFactorial(number - 1, result * number);
    }
}

tailRecursiveFactorial(5); // 120
```

In this case, the function is executing in the following steps.

```js
Step 1: tailRecursiveFactorial(5, 1)
Step 2: tailRecursiveFactorial(4, 5)
Step 3: tailRecursiveFactorial(3, 20)
Step 4: tailRecursiveFactorial(2, 60)
Step 5: tailRecursiveFactorial(1, 120)
```

This type requires fewer operations and needs fewer items on a stack, which means more performant execution.

***

For more, you can follow me on [Twitter](https://twitter.com/hi_iam_chris_), [LinkedIn](https://www.linkedin.com/in/kpajtasev/), [GitHub](https://github.com/kristijan-pajtasev/), or [Instagram](https://www.instagram.com/hi_iam_chris_/).