function factorialize(num) {
var result = 1;
if (num > 0) {
for (var i = 1; i <= num; i++) {
result = result * i;
}
}
num = 1;
return result;
}
factorialize(-7);
I know that there is other more simple solution but I only wanted to focus on my way of thinking .
I am doing these challenges for a week to get used to the “logical thinking” and it is really hard. I hope 1 day I get better at writing because the are a lot of amazing terms, methods, function, prototypes to learn =)
function factorialize(num) {
var result = 1; // result is assigned with 1
if (num > 0) { // if this condition is true, then result will be assigned with other value.
for (var i = 1; i <= num; i++) {
result = result * i;
}
}
The factorial of 1 is 1, you can change your if condition so that your for loop is not executed in that case (like you did for for num = 0).
Instead of result = result * i you can use the equivalent result *= i, which means "multiply result by i".
With your function, the factorial of any negative number would be 1, which is wrong. You should return another value (for example undefined) if someone tries to find the factorial of a negative number.
You can format your code putting it between backtick characters:
my code
This results in something nicer to read, so it is easier for other to help you.
function factorialize(num) {
var result = 1; // result is assigned with 1
if (num > 0) { // if this condition is true, then result will be assigned with other value.
for (var i = 1; i <= num; i++) {
result = result * i;
}
}
return result;
}
function factorialize(num) {
var result = 1; // result is assigned with 1
if (num > 0) { // if this condition is true, then result will be assigned with other value.
for (var i = 1; i <= num; i++) {
result = result * i;
}
}
if (num < 0) {
result = undefined;
}
return result;
}
factorialize(-7);
Generally you should check error cases first, so your program doesn’t do unnecessary work.
Put your second if at the beginning. And you don’t have to do result = undefined - if you return without value it defaults to undefined. So the first line could be:
function factorialize(num) {
if (num < 0) return; // number is invalid, return undefined
...
...