Tell us what’s happening:
I understand how to use recursion to take a number and count it down to 1, but I am having an issue figuring out how to multiply each iteration of the number as it is counting down.
I know 5 should output 120, but I am getting 30. What am I missing?
I know there are other threads with this issue but I am not looking for a solution. I am looking to understand this with minimal assistance.
Your code so far
let factorialize = (num) => {
if (num === 0) { return
} else {
return num * (num + 1);
factorialize(num - 1);
return num;
}
}
console.log(factorialize(5));
/* How can I accurately multiply each iteration of num as it is going through recursion? */
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0.
You don’t really need that, because it will eventually get to the base case and do the same thing, but for now, let’s focus on what should have if num is greater then 1 (based on your code). Also, make sure you are using || and not | in the above code.
So let’s look at factorialize(2). This would need to process something like:
2 * factorialize(1)
and we already have established what factorialize(1) will return.
And then factorialize(3) would process something like:
3 * factorialize(2) * factorialize(1)
Using this processing logic, what would your return statement if num is greater than 1 need to look like, so that you eventually end up calling factorialize(1) (or 0 if you get rid of the OR condition in the if statement)?