Factorialize a Number!

Factorialize a Number!
0

#1

Tell us what’s happening:

It seems to be the for loop running properly but it does not hold the values of factorialnum and multiply them to each other while the for loop runs every time. How do I get it fixed?

Note: I do not want to use the solution from Get a Hint, I want the for loop to get it fixed.

Your code so far


function factorialize(num) {
  var factorialnum;
 if (num === 0 || num === 1){
   return 1;
 }

 for (var i = 1; i < num; i++){

   factorialnum = num * i;
 } 
  
  
  
  
  
  return factorialnum;
}

factorialize(5);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number


#2

You are reassigning the value of factorial based on multiplying num * i. Basically, you are “erasing” the history of factorialnum during each iteration. What that means is at the end of each for loop iteration it will only contain the value that the current value of i multiplied by 5 (num) is.

You only want to multiple factorialnum by 5 one time and not during each iteration. Think about how you could do not and use the previous value of factorialnum to calculate the new value of factorialnum in some way.

Hint: Think about using the += operator.


#3

I still did not get it.


#4

Do you understand that the code you wrote above is always reassigning a new value to factorialnum based ONLY on i and num during each iteration?

Do you understand what finalVal would be in the following code?

var val = 20;
val += 30;
val +=50;
var finalVal = val;

#5

Yes I got that. when I put factorialize(5), will have a value of 20, and if I put factorialize(6) will have a value of 30 which will keep the last value after each iteration because factorialnum is overwritten with each iteration . That is not what I did not get, the problem is when you gave me a hint to use the += operator I did not get where to put it in the code to make it work. I would assume that I need to do some changes to make factorialnum keep the same value and multiply it with each iteration OR define a different variable with empty array and add each factorialnum value with each iteration to it and then multiply all of them at once and return it.

Sure.

var val = 20;
val = val + 30 //50
val = val + 50  //100
var finalVal = 100;

#6

This is exactly the solution I was alluding to with respect to using the += operator.