I saw this about recursive function -
function factorial( n ) {
if ( n === 1 ) {
return 1;
}
return n * factorial( n - 1 );
}
And the explanation being given here -
factorial( 3 ) is 3 x factorial( 2 ).
factorial( 2 ) is 2 x factorial( 1 ).
factorial( 1 ) meets our if condition, so it’s just 1.
Now some how as i am thinking how can factorial(2) or factorial(3) resolve to values of 2 , 3 in this case , as there is no where saying it should return n …
Also how do they multiply with each other after each step
I am really sorry i was able to grasp it some 6 months back but right now i am totally at loss …
Thanks
Consider factorial(3)
as an example, the first iteration the code runs as commented below:
function factorial( n ) {
// n = 3, this is skipped
if ( n === 1 ) {
return 1;
}
// returns 3 * factorial(2)
return n * factorial( n - 1 );
}
The code continues running because the factorial(2)
is called, and factorial(2)
runs as follows:
function factorial( n ) {
// n = 2, this is skipped
if ( n === 1 ) {
return 1;
}
// returns 2 * factorial(1)
return n * factorial( n - 1 );
}
Therefore, at this point, factorial(3)
evaluates to 3 * 2 * factorial(1)
. The code continues running but since factorial(1)
returns 1, the code stops and therefore factorial(3)
evaluates to 3 * 2 * 1
, which is 6 as you would expect. I think you may have “forgotten” about some of the code that have already been evaluated as you were following through the logic (for example, the 3 *
part in 3 * factorial(2)
in the first iteration mentioned above). I hope that helps. 
1 Like
@honmanyau - thanks i was not able to visualize the fact that the code will run function inside function inside function till it gets to one … which you helped with …
1 Like
Never be sorry to ask, unless you didn’t even tried to understand.
Recursive functions are not “such a basic question” anyway.
1 Like