Factorialize a number need explanation please

Factorialize a number need explanation please
0

#1

Hello,

Can someone point me to the right direction please? I’m trying to understand what’s happening below:

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

factorialize(5);

What I understand is:

I set i to 1; if num is the same or bigger than 1, perform this loop; decrease num by 1 every time loop runs
I understand this line (i think so) but I’m struggling with the second line:

i = num * i;

I know loop needs to run 5 times because our num number is 5.
After the first loop, is:

i = num * i; the same as i = 5 * i; ?

or is:

i = num * i; the same as i = 4 * i; ?

I’m confused because the first line of my loop says that it will decrease num by 1 every time the loop runs so if I run:

for (var i = 1; num >= 1; num–) {
i = num * 1; num on this line should be 4 because i have decreased it by 1 but then it would not make sense
}

I just don’t understand why on the second line the num is still 5, not 4, after the first loop.

I hope you understand me. If not, please let me know :slight_smile:

Thank you for help.


#2

hello
You start loop with: i=1, num=5
operation in first loop: make calculation on right: num * i (5 * 1) and now value is assigned to the variable to the left of the operator so now i=5

next loop : i=5, (decreasing num) num=num-1 (5-1=4 ) so now num=4
operation in second loop: make calculation on right: num * i (4 * 5) and now value is assigned to the variable to the left of the operator so now i=20

etc.


#3

Thank you! Makes little bit more sense.

Dziekuje i pozdrawiam :slight_smile: