Can't understand 2 things, Factorialize a Number

Hello!
1st: why I need to exclude 0 and 1 if the code in curly braces doesn’t execute if var i >= 1(so if var i = 0, 0>=1-false,the loop stops and there’ll happen nothing)?

2nd:

for(var i = 5 - 1; 4 >= 1; 4--) 
  num = 3 * 5 = 15 
for(var i = 3 - 1; 2 >= 1; 2--) 
  num = 15 * 1 etc

I can’t get 120, but how it works? How and when does i-- work ?Why I need to decrement var i which is 4 already, because if I do, it will be 35 not 45.

function factorialize(num) {
  if (num === 0 || num === 1)
    return 1;
  for (var i = num - 1; i >= 1; i--) {
    num *= i;
  }
  return num;
}
factorialize(5);

It’s not clear to me what you are asking.

well most of it was explained in that edit although I would recommend rand to separate his answer from the OP question

you don’t need that if statement for this for loop approach so just remove it but if you were to use recursion then yeah you would need an if statement there. You might have mixed those two together creating that?
Like this one

function factorialize(num) {
	if (num == 0) 
		return 1;
	else
		return num * factorialize(num-1);
}

You are misunderstanding how the above code works. The i = num - 1 is initial value of i for the loop, then as each consecutive iteration occurs, i gets reduced by one with the i–

So, in the first iteration, we start with i = 4 and num = 5, so the num *= i evaluates to num = 5 * 4 which is 20.

In the second iteration, i = 3 and num = 20, so the num *= i evaluates to num = 20 * 3 which is 60.

In the third iteration, i = 2 and num = 60, so the num *= i evaluates to num = 60 * 2 which is 120.

In the 4th iteration, i = 1 and num = 120, so the num *= i evaluates to num = 120 * 1 which is 120.

There is no 5th iteration, because i becomes 0 which is not >= 1, so the for loop does not continue and num of 120 is returned.

2 Likes