I am trying to create a simple recursive JavaScript function that produces factorials. I think I exhaust local memory in the callstack when running the code below and likely trigger an infinite recursion.
*Note: I want to use recursion to solve it.
function factorial(num, factor) {
//loop through descending order multiply
if (num === 1) {
return newNum
}
let newNum = num --;
let newProduct = num * newNum;
//recurse
return factorial(newNum, newProduct);
}
// Test cases
console.log(factorial(4)); // -> 24
console.log(factorial(6)); // -> 720
console.log(factorial(0)); // -> 1
Any suggestions as to how and why I should modify my above code.