b = 6
6 * 5 * 4 * 3 * 2 * 1
so we need to get the num less than before
so
function factorial(b){
if(b === 0){
return 1
}
else {
b * factorial(b-1)
}
6 * factorial(6-1){
if(5 === 0){return 1} // false
else {5 * factorial(5-1) //true
{if(4 === 0){return 1} // false
else {4*factorial(4-1) //true
{if(3 === 0){return 1} // false
else {3 * factorial(3-1) //true
{if(2 === 0){return 1} //false
else {2 * factorial(2-1) //true
{if(1 === 0){return 1} // false
else {1 * factorial(1 -1) //true
{if(0 === 0){return 1} //true
else {0 * factorial(0-1)} // false
}}}}}}}}}}}}
here the function dosent call in every return but after calling upto n === 0 it saves each function value and multiple from right to left
like factorial(0) = 1
factorial(1) * factorial(0) = 1 * 1
factorial(2) * factorial(1) = 2 * 1
factorial(3) * factorial(2) = 3 * 2
factorial(4) * factorial(3) = 4 * 6
factorial(5) * factorial(4) = 5 * 24
factorial(6) * factorial(5) = 6 * 120
it call the function after stacking in top order
the last called function is on top of stack
Top comments (0)