Factorising a Number (my code works but seems weird to me))

Tell us what’s happening:
So the first problem is that my code does work, but it seems to me that my solution is wrong. The second problem is that thecode (you can see the code below in Your code so far ) doesn’t work in my console. But if I declare ‘sum’ and ‘arrFac’ before function it works. I don’t understand why does it happen.

Your code so far


function factorialize(num) {
let sum = 1
let arrFac = []
for(let i = num; i>0; i--){
  arrFac.push(i)
  sum *=i
}
return sum;
}

factorialize(5);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 YaBrowser/19.12.0.358 Yowser/2.5 Safari/537.36.

Challenge: Factorialize a Number

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

I wrote code in Visual studio code, and when I open file from VS code in my console it doesn’t work.
But if I declare variables before function it works.

what do you see that make you think it doesn’t work?

Sure. :slight_smile: Second screenshot shows code that was commented on the first screenshot.

For the second one, you do not have console.log(factorialize(5)); like your first example. It has nothing to do with where you put the variable declarations.

I can’t believe I made such a stupid mistake, thank you!

One thing seems quite weird to me too. Why do need arrFac, what’s the use of it?

1 Like

So the idea was to create an array wich will contain all numbers from 1 to num(5 in this example), and then multiply every element in array.

but you are already multiplying the numbers before putting them all in the array, do you really need the array? you are not doing anything with the array