I dont understand the following code. Also how recursion works in js.
function a(num){
if(num===1){return 1;}
return num*a(num-1);
}
a(4);
for example from the code above, the way I see it was this :
- function checks whether num===1, if it is return 1
- if it is not,
return num=num*(num-1);
recursion should be repetitive right? I have seen some memes/jokes about recursion is like keep repeating a part of the sentences forever and ever…
in my mind after 4*3, the result will be returned and done.
in another word I do not understand the difference between these two set of code 
- normal code :
function b(num) {
return num * (num - 1);
}
b(4);
- recursion
function a(num) {
if (num === 1) { return 1; }
return num * a(num - 1);
}
a(4);
could someone explain this to me?
I understand that 4!=4x3x2x1, that part is easy.
oh wait… I think I kind of understand it now…
recursion happens when you write a function and that function calls itself
So a way I can understand this is :
return num*a(num-1);
is making a function call, and this time the parameter is num-1
so what we get is this kind of operation:
4*a(3)
-
4*3*a(2)
// the 4 times part stays the same
-
4*3*2*a(1)
// same, the 4 times 3 part stays the same
-
4*3*2*1
. // because we already set a(1)===1
Is this correct???
Yeah here’s how i see it,
Iteration |
num |
a() returns |
a(num-1) |
Result |
notes |
1 |
4 |
4*a(num -1) |
6 |
24 |
Third fully evaluated factorial |
2 |
3 |
3*a(num -1) |
2 |
6 |
Second fully evaluated factorial |
3 |
2 |
2*a(num -1) |
1 |
2 |
First fully evaluated factorial |
I think the main point is that the recursive function does not fully evaluate and return a number until num=2
, i.e. till num-1 ===1
, in all other cases of the num
parameter, it will return a function.
Once it reaches that number, then notice how the result is transferred up the chain to evaluate a(num-1) . i.e. the result 2 is carried up to the 2nd iteration and the result 6 to the 1st iteration and so forth, closely resembling the mathematical definition of a factorial.