Let's talk Recursion

I am confused quite a lot about the concept of recursion and how it works, I’d like some help in Understanding it in simpler terms. I tried reading the freecodecamp article on it, but didn’t seem to be as clear. Thank you!

It would help if you could breakdown what part of recursion confuses you. Without more information, we can’t do much but point you toward full articles.

The idea in general confuses me, If the articles are good, then please do lead me there.

Hi @Brijesh,

I suggest you go through the tutorial here: https://javascript.info/recursion

But in simple terms, recursion is a function that runs itself over and over again until the final condition is met.

1 Like

HI @Brijesh!

You could also look into Colt Steele’s video on recursion.

Also, I’ll try to do my best to show you how it works with an FCC example. If my explanation is confusing then you can totally ignore it :smile:

I’ll wrap this problem in spoiler tags since it is one of the FCC challenges but hopefully this will help.

function rangeOfNumbers(startNum, endNum) {
if (startNum === endNum) {
  return [startNum];
} else {
  var numbers = rangeOfNumbers(startNum, endNum - 1);
  numbers.push(endNum);
return numbers;
}
};

This is the base case in recursion.
if (startNum === endNum)

and this is the recursive case or (function that calls itself)
rangeOfNumbers(startNum, endNum - 1)

Here is what is happening in the computer.

Let’s say start num is 1 and end num is 5.

The computer will check the if statement first
Is 1 equal to 5? No.

So then it goes to the else statement
rangeOfNumbers(1, 5 - 1) or rangeOfNumbers(1, 4)

So then we start again
The computer will check the if statement first
Is 1 equal to 4? No.

Then we move to the else statement and keep repeating this process until we get to is 1 === 1? Yes

Then we return [1]

So now the numbers array is [1]

Then we execute these lines of code
numbers.push(2);
Numbers array is [1,2]
numbers.push(3);
Numbers array is [1,2,3]
numbers.push(4);
Numbers array is [1,2,3,4]
numbers.push(5);
Numbers array is [1,2,3,4,5]

Hopefully that helps!

3 Likes