DEV Community

Clint Maruti
Clint Maruti

Posted on

Introduction To Recursion & The Call Stack

What is Recursion?

Recursion is when a function calls itself.

Syntax:

function func(){
   if(/*base case*/){
      return something  
   } else { // recusive case
      func()
   }
}
Enter fullscreen mode Exit fullscreen mode

Example

Let's write a function that returns the factorial of a number passed in as argument.

The factorial of a number is that number multiplied by every number from itself down to one.

4! = 4 * 3 * 2 * 1 = 24
3! = 3 * 2 * 1 = 6

function factorial(num){
   if (num === 1) { // The factorial of 1 is 1 so our base case is set
      return num;
   } else {
      return num * factorial(num -1) // Recursive case 
   }
}
Enter fullscreen mode Exit fullscreen mode

The best way to understand this is by going through the function step by step. To visualize, we will use a Call stack. Please click here if you don't know what a call stack is before proceeding.

TL;DR
Call Stack represents what order the functions are being called in and what variables they are being called with.

Order:

  1. factorial(4) => 4
  2. factorial(3) => 3
  3. factorial(2) => 2
  4. factorial(1) => 1 * (1-1) = 1 = base case

4 * 3 * 2 * 1 = 24

Okay, I know for those who are not acquainted with recursion may find this cumbersome. I urge you to read more about it.

But the baseline is, a recursive function will continue to call itself until the base case is fulfilled!

See you in the next one!

Top comments (0)