 # Algorithm Scripting: Factorialize a Number

I’m trying to solve the following FCC challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number

This is the code I used and it doesn’t work:

function factorialize(num) {
for (var i = num - 1; i >= 0; i–) {
num *= i
};
return num;
}

factorialize(5);

Then I removed the “=” from the “i >= 0” and it worked for all the tests except the last one:
“factorialize(0) should return 1.”

Should I proceed with an if / else statement or is there a better way of doing it?

Thank you.

By adding an if-statement my code worked. This is the finished product:

function factorialize(num) {
if (num > 1) {
for (var i = num - 1; i > 0; i–) {
num *= i
};
}
else if (num === 0) {
num = 1;
}
return num;
}

factorialize(5);

Is it correct? It seems to me that I “cheated” by adding an else statement for the num === 0.

You are given a condition that if num = 0, then return 1. Using an if-else statement for this is correct. Generally, you will want to check for the special conditions first, for better syntax and readability.

``````function factorialize(num) {
if (num === 0)
return 1;
else {
for (var i = num - 1; i > 0; i–-) {
num *= i;
};
}
return num;
}
``````