As I want to use the value num from the function’s paramater as a limit in my for loop, the console.log says that my loop is becoming infinite when I write
for(i = 1; i <= num; i++) {
}
On the other had, if I hardcoe the number 5 in i <= 5; the loop works fine. This leads me to think num isn’t a valid number. Still console.log(num); does output the number 5. And console.log(Number(num)); also. Confusing…
function factorialize(num) { console.log(num); for (var i = 1; i <= num; i++) { console.log("num before calc: " + num); num *= num - 1; } return num; } factorialize(5);
… And yes, now I get it. I need to protect ‘num’ from the calculation if I want to use it as an evaluation. Otherwise the condition keeps changing and keeps on fueling the loop.
Yes, don’t change value of num.
You need another variable, to keep track of the product.
and initialize this variable to 1, otherwise if it’s initialized to 0 (zero), then your final answer will always be 0.