HOW TO UNDERSTAND RECURSION WITH EXAMPLES

MoisesN
4 min readFeb 5, 2021

I was doing a very interesting free certification called “FreeCodeCamp” (I totally recommend it for anyone who start coding Javascript), when I got stuck in the part “Recursion”. Darn it is so hard to understand I thought, So here I am trying to explain it:

To begin, lets read some info about recursion from a reliable source:

MDN Web says that Recursion is when a function is called itself, and there are three ways to accomplish it:

  • The function’s name
  • Arguments.callee
  • An in-scope variable that refers to the function

So let’s start giving examples to understand, the basic is how to define a function:

function nameOfFunction(‘arguments if you need’){

‘Magic goes here’

}

Now here is a declaration to make a function to call itself and the outputs it would return until it reaches the condition of being more than zero

Now lets call it and use the argument of 5:

What happens is that the function is nested, so second console.log is executed until it reaches the condition of being more than zero, and then it prints the second console log until it reaches the number we used as initial argument.

Let’s se another example with a function to square a number:

You just need to analyze for a minute what happens, until the inner function reaches pow = 1, it returns it so the inner number1 is multiplied by itself and goes out again multiplying the number itself as many times as needed. Here is the output:

Something more complex, lets fill an array with 10 random numbers and they have to be integers from 10 to 20

Using Math.floor(), you get the round of the function Math.random which gives you a decimal number from 0 to 1 and you multiply that for the range of numbers (20 minus 10 equal to 10). then until the length of the container is 10, you repeat the function casting it at the end of the same function.

Now lets solve the exercises in FreeCootCamp starting from number 100 Replace Loops Using Recursion:

What happens here is that you would return the array plus zero in case that argument n is zero. Else you would add each number of the array until it reaches zero

Now the last two exercises, first Use Recursion to Create a Countdown:

It is easy if you use as base the example given, due to the fact that countdown is the oposite than countup, you just need to swap the method .push() for .unshift() which insert the value at the beginning of the array.

Last exercise: Use Recursion to Create a Range of Numbers:

This is one of the possible answers, where is declared the variable total to store the method .push(), the cycle breaks when startNum is equal to endNum.

Here is another article where you can find more information about recursion

Learn and Understand Recursion in JavaScript

--

--