Factorialize Number Challenge

The following code works but is not accepted being accepted, can anybody tell me why?

var x=0;
var fact=1;

function factorialize(num) {

while ( x < num){

x=x+1;

fact = fact*x;

}
return fact;

}

factorialize(0);

Because of global variables. FCC tester doesn’t reset global variable between tests.

You need to put the variables x and fact inside of your function. Since they’re not in the function, they’re in a global scope. This means that after you run your factorialize function, x and fact are set to a new value, and they remain at that value after the function finishes. So using your code, if I do factorialize(5) I get 120, which is correct. But if afterwards I do factorialize(3), I get 120.

I get 120 because fact is still 120 since it’s a global variable. X is also set to 5, so it doesn’t do any calculations (since I passed 3 in as an argument it won’t even bother doing anything).

Move the variables inside of the function so their scope is only inside of the function. So once the function finishes, the variables will basically be destroyed when the function returns.

hello RAN27,

how are you testing your code if you say it works?

NathanMcSparran - global to local makes sense. Thnx!

alfasf - I was testing in the space they provided and it worked for all their cases.