Basic Algorithm Scripting - Factorialize a Number

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

Link to the challenge:

What happens if you run it twice?

console.log(factorialize(5));
console.log(factorialize(5));

Be wary of global variables.

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.

1 Like

Yes, indeed, though can you explain why the challenge passes if you simply remove the console.logs altogether?

Right, it could be “fixed” that way, but that does not fix the overall problem.

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.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.