Understanding factorialize(0)

Tell us what’s happening:
I completed this challenge using for loops

  1. Use a for loop to create an array of factorialize(num)
  2. Initialize var sum = 1
    then with my second for loop use an assignment operator to multiply sum with each new passed in loop.

I am having a hard time understanding why when factorialize(0) is passed in
var sum = 1 since 0*1 = 0

Can someone help me understand how when 0 is passed in sum is returning 0

Thanks,
Teak

Your code so far

function factorialize(num) {
  
  var arrOfNum = [];
  var sum = 1;

  for (var i = 1; i <= num ; i++) {
    arrOfNum.push(i);
  }
  
  for (var j = 1 ; j<= arrOfNum.length ; j++) {
    sum *= j;
  }
  
  return sum;
  
}

factorialize(0);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36.

Link to the challenge:

I meant
Can someone help me understand how when 0 is passed in sum is returning 1

You set the value of sum to 1.

After that the for loops will do nothing:

  1. var i =1; i <= num; i++
    i is never less than or equal to num, so the loop does not run (not even once)
    So after the first loop arrOfNum is still empty ([]).
  2. var j = 1; j <= arrOfNum.length; j++
    Same as the first loop: j is never less than arrOfNum.length because the length is zero.

So none of the loops run, so effectively you are just doing:

function factorialize(num) {
  
  var arrOfNum = [];
  var sum = 1;
  
  return sum;  
}

Which returns 1

1 Like