Understanding Recursion

Mirror in the Mirror

This being my first post on programming, I decided to help my readers in understanding the topic of recursion in my own way since it was one of those topics which gave me a tough time in understanding it. So lets begin:

What is Recursion -_- ?

In simple words, recursion is the process in which a function calls itself till a given condition is met or infinity(in case if it lacks a proper condition).

To understand this better, lets solve a basic example of

Finding factorial of a given number:

Above is a simple JavaScript function which is given the argument ‘ 3 ’.

So what happens next ?

Step 1: The number ‘ 3 ’ gets passed to the function and first the condition that if it is greater than ‘ 1 ’ is checked.

Since it is true, it goes to the next step where a return statement is being called with an expression (3 * factorialize(3–1)). And this is the most important part of recursion.Basically return statement is the point where the function calls itself again.In this our case there is an expression i.e 3 * factorialize(3–1).

Step 2: Now at this point, before the expression is resolved, the function is again called, now with a different value (i.e 3–1=2) being passed as an argument. Below is an illustration how our function virtually looks like

So, this continues till the if condition is false at which the function returns one. So the expression gets solve in the following order:

3*(2*(1))) = 6, and there we go. Recursion is generally chosen over Loops by the developer since it is believed to be robust.

Hope this post was helpful to move a step forward in your developer journey! :)