I know there are many threads for recursion here. And technically I do understand the principle behind recursion, I'm just more of curious as to where the actual recursion counter is stored or how does the compiler keep track of it
This is probably better understood by code. I have created a simple recursion function in javascript.
function factorial(number){
if (number > 1) {
return number * factorial(number - 1);
} else {
return number;
}
}
Now, everybody understands how this works. We call a recursive function on the factorial which repeats recursively until a function end.
My question would be, how come the factorial function stops executing the recursion at the correct time? If we tried to debug the function in our mind, my understanding is, it would look something like this:
Let's say we called factorial(3);
- Function Invoked -> Load Arguments
- Calculcate the IF condition -> 3 > 1 -> apply recursive function
- 3 * recursive(2) * recursive(1) => 3 * 2 * 1 = 6
Now my question is, how is that possible? How come a) if we reduced the recursive counter to 1, we didn't enter the else {
statement given it should be evaluated as false, and b) how come the recursive counter knew, to loop the recursive function only number-Nth amount of times?
For better illustration, I added the following line of code
document.write("entered with number " + number + "</br>");
so we'll print it out every time we enter the if condition.
function factorial(number){
if (number > 1) {
document.write("entered with number " + number + "</br>");
return number * factorial(number - 1);
} else {
return number;
}
}
document.write(factorial(3) + "<br/>");
As you can see, the if condition if condition evaluated as true and printed out the message for 3 and 2. How come the counter didn't loop lower and how come we never returned to the initial else { return number; }
if we called the recursive operation on factorial(2-1)
?
It is pretty difficult question to word, so if you have any idea on how to formulate it better, feel free to edit my question!