JS Objects 1 ... And the good!


#1

In the introduction to object 1 course, I can't pass the third challenge "... And the good!". This is my code:

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

Can anyone tell me why this won't work? Thanks


#2

FizzBuzz needs to be your first if condition. The other two, fizz and buzz, need to be else if statements. the reason why is because if the number is 15, it will print Fizz instead of FizzBuzz because Fizz is the option that comes first. I hope this makes sense...


#3

That didn't work. It's still saying that I printed out the wrong number of items.


#4

Post your updated code.


#5

You're always printing the number, shouldn't that happen only when it's not fizz/buzz?


#6

Yes you're right. There's some stuff logically wrong with this code. There should be an else statement that prints the number at the end. Additionally, what I said was not correct because Their if and else if conditionals all were very specific and had && so that FizzBuzz should print correctly. I think that the issue was actually just not having an else statement for the number to print.


#7

In the instructions it says to print out the numbers 1-20, then "Fizz" if the number is divisible by 3, "Buzz" if the number is divisible by 5, and "FizzBuzz" if the number is divisible by 3 and 5. Then it says "otherwise, just print out the number". So I need to write an else statement to just print out the number after I already printed out the numbers 1-20?


#8

I don't have the instructions immediately available to me.
FizzBuzz is a common problem presented to beginners, the problem statement usually says to replace the numbers that are divisible by 3 or 5.

You can probably answer your own question by reading the instructions.


#9

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