Factorialize a number - what am I doing wrong?

I am aiming to have num multiply each iteration of i. Eg. let result = (5 * 1) * (52) * (53) * (54) * (55 ).

I’m not quite sure how to translate that intention to code.

Your code so far


function factorialize(num) {

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

let result = num * i

return result

} 
 


}

console.log(factorialize(5));

Your browser information:

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

Challenge: Factorialize a Number

Link to the challenge:

Sorry, just realised I my solution is off anyway

I have solved the challenge, however, I am a little unclear on why I had to include the initial part of the code (the section that is commented out). Particularly the result -1; line.


function factorialize(num) {

   //var i;
  // var result;
  // result = 1;

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

result = result * i;


} 
 
return result

}

console.log(factorialize(5));

Your browser information:

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

Challenge: Factorialize a Number

Link to the challenge:

This line declares i. It is unnecessary. You declare i in the for loop and initialise it with a value.

This line declares result so it does not throw an error when you call it in the for loop.

This line is necessary to initialise the result variable with a value of 1. Without this, you’d get NaN when you tried to multiply result * i.

The entire commented section could be replaced just with var result = 1 and the code would still function.

1 Like

Thanks for providing the clarity. One more question: why does the code return a different result depending on where the [ var result = 1 ] declaration is placed? For example, if I declare result = 1 in the for loop block, the function will return something different.

Because you are effectively resetting the value of result to 1 with each iteration of the loop.

1 Like