Factorialize a number Solution 1 iteration explanation required

for (var product = 1; num > 0; num–) {
product *= num;
}
return product;

in regards to this part for solution, Could someone explain the use of var product = 1 in the for loop and why it is then returned outside that statement? I dont understand why it needs to be set to 1 or iterated down and not up like:

for (i = 0; i >=num; i++)

  **Your code so far**

function factorialize(num) {
return num;
}

factorialize(5);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.55

Challenge: Factorialize a Number

Link to the challenge:

Because if you multiply by 0, you will only ever get 0.

2 Likes

That var product=0 bit should be initialized before the loop, doing it that way is misleading. But the idea is, by starting product at 1, num*product Will initially equal num.

We could have skipped an iteration and set var product=num initially, and then started the loop with --num; num > 0; num-- but that might have been just as confusing. Better to start product at one, so the loop makes sense imo

1 Like

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