4! = 4 x 3 x 2 x 1;
function factorial(num) {
let total = 1;
for (let i = num; i > 1; i--) {
total = total * 1
}
return total
}
factorial(4) // 4 * 3 * 2 * 1 = 24
function factorial(num) {
return num * factorial(num - 1);
}
factorial(4) // 4 * 3 * 2 * 1 = 24
return num * factorial(num - 1);
if num is 5 --> 5 x 4 x 3 x 2 x 1 x 0 x -1 x -2 x -3
With just that, num becomes an infinite loop.
You need an ENDPOINT (Base case)
function factorial(num) {
if(num === 1) return 1;
return num * factorial(num - 1);
}
factorial(4) // 4 * 3 * 2 * 1 = 24
factorial(5) // 5 * 4 * 3 * 2 * 1 = 120