...And the good! FizzBuzz Not Printing


#1

No matter what I do, and how many other examples I've compared my code to, I cannot get FizzBuzz to print for #15 in the sequence that prints to the console. I keep getting the error message, "Oops, try again. You printed Fizz when you should have printed FizzBuzz." What am I doing wrong?


for (var x = 1; x < 21; x++) {
    if (x % 3 === 0) {
        console.log("Fizz");
    } else if (x % 5 === 0) {
        console.log("Buzz");
    } else if (x % 3 === 0 && x % 5 === 0) {
        console.log("FizzBuzz");
    } else {
        console.log(x);
    }
};


#2

Try writing this line,

like this,

else if ((i % 3 === 0) && (i % 5 === 0)){

or even make this your if statement,

if ((i % 3 === 0) && (i % 5 === 0)){


#3

I ended up having to write it first before the other clauses, as an 'if' clause, and not as an 'else if' clause. Any idea why this works like this?


#4

Because of the loop you see as it loops through the numbers it is checking ecah conditional statement and because of control flow allowing it too check if a number is divisible both by 3 and 5 first will make sure it catches those 'unique'numbers but you see if your code is like this,

By the time your loop reaches this line,

else if (x % 3 === 0 && x % 5 === 0) {

There is no number left that is divisible both by 5 and 3, thus causing an error. :slight_smile:


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.