Recursion and the Call Stack Explained By Reading A Book
Tags: beginners, webdev, tutorial
Published: 2020-01-22 02:14:19

---
title: Recursion and the Call Stack Explained By Reading A Book
published: true
description: If you have ever read a book in English, then you can understand recursion 🙂
tags: #beginners, #webdev, #tutorial
cover_image: https://i2.wp.com/blog.codeanalogies.com/wp-content/uploads/2020/01/aaron-burden-G6G93jtU1vE-unsplash.jpg?resize=900%2C676&ssl=1
---


Recursion is one of the most exciting principles of all programming languages.

 

A non-recursive function (in other words, the functions that you have used in the past) will run once every time it is called, and output via a return statement.

 

However, a _recursive_ function can be called once and then **call itself an undetermined number of times** before combining the output of all the function calls in one return statement.

 

It kind of looks like this. 

Static version:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ppp6jbdbobm3fw9bf1vz.jpg)


Dynamic version:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/u206b4q3jinh5ghhbc0b.jpg)


The idea that a single function can be called one to infinity times via a single statement is what makes it so exciting!

 

At the same time, it is difficult to think of a real-world analogy to this situation. And it gets especially difficult once we discuss the **call stack** , which we will cover later.

 

Some have suggested a series of infinite boxes:

  ![](https://i1.wp.com/blog.codeanalogies.com/wp-content/uploads/2020/01/image-1.png?fit=730%2C514&ssl=1)*Image Cred: [Grokking Algorithm](https://www.manning.com/books/grokking-algorithms)*
 

Others have suggested the imagery of “Russian nesting dolls”:

  ![Image result for recursion russian dolls](https://i1.wp.com/miro.medium.com/max/669/1*Hgviugi5d0AZcFgy1-xVqQ.jpeg?w=730&ssl=1) 

However, this is also unhelpful when understanding the call stack.

 

So, in this tutorial, we will show two popular examples of recursion, and build a visual language for understanding the function and the **call stack** , which determines how to make sense of the many function calls in a row.

 

Before continuing with this tutorial, you should have a firm understanding of functions in JavaScript. [Check out this guide to arrow functions](https://blog.codeanalogies.com/2019/04/14/javascripts-arrow-functions-explained-by-going-down-a-slide/) to learn more.

 
### Example 1- Factorials
 

Factorials are the most popular example of recursion.

 

You might be familiar with factorials from algebra class.

 

They are expressed like: 3!

 

And that notation evaluates to 3\*2\*1, or 6.

 

We could express this as a “for” loop where we update a variable outside the loop:

 
```javascript
let factorial = 4;
let result = 1;

for (i=factorial; i>= 1; i--){
    result = result*i;
}
```
 

But, here we will use recursion instead. Rather than have a loop that updates a variable outside of its scope, we can use recursion with a function and have _n-1_ calls, where _n_ is the factorial we want to find.

 

I will show the code first, and then we can evaluate how it works.

 
```javascript
let getFactorial = (num) => {
  if (num == 1)
    return 1;
  else
    return num * getFactorial(num-1);
}

getFactorial(4);
// 24
```
 

Woah! This accomplishes the same thing as the code block above.

 

But, if you look at line 5, you can see that the _return_ statement includes a reference to the function itself.

 

So… when does this function return a final value, exactly? How do we link the 4 calls of the function together to return the value of 24?

 

This is where the **call stack** becomes useful. It determines the rules for the order that these function calls will return.

 

But, now we are stacking two concepts on top of each other: recursion and call stack. That’s a lot at once.

 

In order to visualize the call stack, let’s think of a stack that builds **from left to right**. Every time a block gets added, it is added to the left side of the stack and pushes the other blocks to the right.

 

So, as we go through this recursive function, we generate a stack like this:

  ![](https://i2.wp.com/blog.codeanalogies.com/wp-content/uploads/2020/01/recursionGIFsNum1.gif?fit=720%2C540&ssl=1) 

The call stack is being generated at the bottom of the screen throughout the GIF above. At the end, we are left with 1\*2\*3\*4 which results in 24.

 

The call stack is composed of 4 function calls, and **none of them run until the function returns 1**. They sit on the stack until the last value is added, in this case 1.

 

This is because each of the first 3 calls includes a reference to the next call on the stack!

 

So, when num=4, the function returns 4\*getFactorial(3). Of course, that cannot actually return a value until we know the value of getFactorial(3). That’s why we need a call stack!

 

So, recursion allows a function to be called an indefinite number of times in a row AND it updates a call stack, which returns a value after the final call has been run.

 

The call stack updates from left to right, and then you can read all the calls in the order they are resolved. Most recent is resolved first, first call resolved last.

 

However, our GIF above did not do a good job of showing this relationship between each call. So, here’s an updated version that shows how all the calls are connected via the _return_ statement:

  ![](https://i2.wp.com/blog.codeanalogies.com/wp-content/uploads/2020/01/recursionGIFsfactorialnum2.gif?fit=720%2C540&ssl=1) 
### Example 2- Splitting a String
 

In the example above, we used a mathematical example that resembled a question from algebra class.

 

This works, but there are also plenty of examples of recursion that go beyond math. In this example, we will show how you can use recursion to manipulate a string.

 

Here’s the challenge: Reverse a string.

 

In other words, return a string with the letters of an input string in the opposite order.

 

You can also do this with a “for” loop, but we will use recursion in this example.

 

Let’s think about how we should reverse the string “cat”.

 

Every time we run a function call, we need to isolate the first or last letter of the string, and then chop off a letter from the string. When we run the function again, we should again grab the first or last letter.

 

At the end, the call stack will allow us to return the letters in the correct order.

 

Here’s the code:

 
```javascript
let testStr = 'cat';

let revStr = (str) => {
  if (str.length == 0)
    return '';
  else
    return revStr(str.substr(1)) + str[0];
};

revStr(testStr);
// 'tac'
```
 

Okay. Let’s dig in, just like we did above.

  ![](https://i0.wp.com/blog.codeanalogies.com/wp-content/uploads/2020/01/recursionex2v1.gif?fit=720%2C540&ssl=1) 

Again, although the GIF above makes it look easy, we need to dig deeper into the final _return_ statement if we want to truly understand these function calls.

 

There is one more important difference in this example compared to the one above- we are doing string concatenation rather than multiplication.

 

Therefore, the order of the strings in that _return_ statement matters quite a bit, because it determines which order we will use for concatenation.

 

Since this is not a series of multiplication problems, the call stack is a little easier to understand. Here is a visual:

![](https://i1.wp.com/blog.codeanalogies.com/wp-content/uploads/2020/01/recursionex2.gif?fit=720%2C540&ssl=1) 

This is why the order of the strings matters so much- as we build the call stack in the GIF above, there is a specific order of the recursive function call and the string fragment (_str[0]_).

 

As we run all the calls in the stack, this order allows us to rebuild the string in the reverse order.

 
### Get The Latest Tutorials

Did you enjoy this tutorial? Check out the [CodeAnalogies blog](https://codeanalogies.com) to get the latest visual web development tutorials.