Reputation:
So my function below is
const message = function (number) {
for (let i = 0; i < 200; i++) {
if (i % 7 == 0 && i % 9 == 0) {
return "Why is the ground shaking";
} else if (i % 7 == 0) {
return "Here is the magic 7";
} else if (i % 9 == 0) {
return "Here is the magic 9";
} else {
return "You have failed";
}
}
};
console.log(message(9));
console.log(message(4));
console.log(message(36));
console.log(message(21));
But it always returns "Why is the ground shaking" not sure why though
Upvotes: 0
Views: 46
Reputation: 1121
You should put i = number
instead of i = 0
const message = function (number) {
for (let i = number; i < 200; i++) {
if (i % 7 == 0 && i % 9 == 0) {
return "Why is the ground shaking";
} else if (i % 7 == 0) {
return "Here is the magic 7";
} else if (i % 9 == 0) {
return "Here is the magic 9";
} else {
return "You have failed";
}
}
};
console.log(message(9));
console.log(message(4));
console.log(message(36));
console.log(message(21));
As mention in the comment section, the for
loop is redundant here.
Your message(number)
function has 1 argument, which is number
, and if you have your if - else
with return
statements, your loop will execute only once on each function call (when the return
occurs). You could put i < 1
or i < 2000
, the result would be the same.
So what you can do is, remove the loop, and simply put your argument (number)
instead of i
in each of your if
statements.
I'm not the best at explaining, but hope this helped.
const message = function (number) {
if (number % 7 == 0 && number % 9 == 0) {
return "Why is the ground shaking";
} else if (number % 7 == 0) {
return "Here is the magic 7";
} else if (number % 9 == 0) {
return "Here is the magic 9";
} else {
return "You have failed";
}
};
console.log(message(9));
console.log(message(4));
console.log(message(36));
console.log(message(21));
Upvotes: 4