Here is the recursion code.
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
console.log(factorial( (n - 1) ));
return n * factorial(n - 1);
}
}
const number = 5;
const result = factorial(number);
console.log(result);`
Output:
1
2
1
6
1
2
1
24
1
2
1
6
1
2
1
120
#Why does the output include repeated ‘1’ and ‘2’ values?
#How does the recursive function behave in this scenario, and why does it produce this specific output?
#Is this behavior related to how recursion works in JavaScript?
3
Answers
Your log prints another recursion, instead of printing the current step
Just Remove
console.log
from the recursive function.New Code