Sam Sam - 2 months ago 17
Javascript Question

Stuck in Codecademy's Javascript fizzbuzz app

Here are Codecademy's instructions:


Print out the numbers from 1 - 20.

For numbers divisible by 3, print out "Fizz".

For numbers divisible by 5, print out "Buzz".

For numbers divisible by both 3 and 5, print out "FizzBuzz" in the
console.

Otherwise, just print out the number.


And here is my code:



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





The problem is that it won't print "FizzBuzz"..for the number 15 it just prints "Fizz" when it should print "FizzBuzz"..

What am I missing here?

Answer

The else if only runs if all of the other statements so far have been false. Since i % 3 is true, the remaing else/if statements will never run. Try something like this:

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