Tell us what’s happening:
this returns 120 which is expeced result, Can someone have a look and let me know what’s wrong with my code. Thanks in advance.
Your code so far
var total = 1;
function factorialize(num) {
total *= num;
if(num > 1) {
factorialize(num-1)
}
return total === 0 ? 1 : total;
}
console.log(factorialize(5));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
Challenge: Basic Algorithm Scripting - Factorialize a Number
You’ve chosen to use a recursive algorithm here. Although I don’t think it is a good use of recursion, it is common to solve this recursively as a learning tool.
In recursion, you commonly have a “base case”, when you know you’ve reached the end and start to “unravel” the recursive calls on the call stack. Before you reach that, usually you return a recursive call that is incomplete, that gets put on the call stack.
I can “explain” it in that it takes advantage of the test not checking that, by resetting for each test. Ultimately it should not use a global variable. That is bad design on not consistent with how recursion is supposed to work. I can open a can of soup with a screwdriver - it doesn’t mean that I’ve used the tool correctly.