This is a simple code for factorial
console.log(`5 fact = ${fact(5)}`)
function fact(num){
if(num == 0) {
return 1;
}else {
console.log(`${num} * fact(${num} - 1)` )
//console.log(num * fact(num - 1))
return num * fact(num - 1)
}
}
i got output when i comment second console inside factorial
5 * fact(5 - 1)
4 * fact(4 - 1)
3 * fact(3 - 1)
2 * fact(2 - 1)
1 * fact(1 - 1)
5 fact = 120
when i uncomment it i got to know some weird things going on inside.
console.log(`5 fact = ${fact(5)}`)
function fact(num){
if(num == 0) {
return 1;
}else {
console.log(`${num} * fact(${num} - 1)` )
console.log(num * fact(num - 1))
return num * fact(num - 1)
}
}
2
1 * fact(1 - 1)
1
24
3 * fact(3 - 1)
2 * fact(2 - 1)
1 * fact(1 - 1)
1
2
1 * fact(1 - 1)
1
6
2 * fact(2 - 1)
1 * fact(1 - 1)
1
2
1 * fact(1 - 1)
1
120
4 * fact(4 - 1)
3 * fact(3 - 1)
2 * fact(2 - 1)
1 * fact(1 - 1)
1
2
1 * fact(1 - 1)
1
6
2 * fact(2 - 1)
1 * fact(1 - 1)
1
2
1 * fact(1 - 1)
1
24
3 * fact(3 - 1)
2 * fact(2 - 1)
1 * fact(1 - 1)
1
2
1 * fact(1 - 1)
1
6
2 * fact(2 - 1)
1 * fact(1 - 1)
1
2
1 * fact(1 - 1)
1
5 fact = 120
Can anyone explain me.
- Where the temporary result will get saved ?
- according to console and code logic it should return 1. But, why it return 120 ?
- what internally happening here ? Is their any limits we need to consider to choose with recursion ?