3 ...and the good!


#1


Why is this not working? It prints out everything well, but FizzBuzz does not work. Please help me :smiley:

//FizzBuzz Game

//Loop
for ( var i = 1; i <= 20; i++) {
    
    //if divisible by 3
    if (i % 3 === 0) {
        console.log("Fizz");
    }
  
    //if divisible by 5
    else if (i % 5 === 0) {
        console.log("Buzz");
    }
    
    //if divisible by 3 and 5
    else if (i % 5 === 0 && i % 3 === 0) {
        console.log("FizzBuzz");
    }
    
    //if not divisible by 3 or 5
    else {
        console.log(i);
    }

};


#2

Move this condition to the top, then follow by 3 and 5, or 5 and 3, then i.

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

}
else if () {

}
else if () {

}
else {

}

#4

I had the same issue, i also had it backward on one part. (seen below)

    if(i === 3 % 0 && i === 5 % 0){
        console.log('FizzBuzz');

once i wrote it correctly and moved it to the top it worked great. (seen below)

for(var i = 1; i < 21; 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);
    }
};

#6

Thanks for the help. I, too, was stuck on this section. Can you tell me what the order of the operations have to do with how the code works though?


#9

@cssrunner58539 I'm am no expert what so ever. but I am pretty sure that the computer reads the code like we read a book. so what ever is read first is taken into account and with...

else if (i % 5 === 0){
        console.log('Buzz');
    } else if (i % 3 === 0){
        console.log('Fizz');

...at the top, it has covered everything both options so it overlooks this code:

(i % 3 === 0 && i % 5 === 0){
        console.log('FizzBuzz');

but with the && option first it it looks for that first and does it. then goes on to what to do if it doesnt === both.

I am not sure why it ignores it if it is out of order but that is just how i figure it works.

anyone feel free to correct me if i am wrong.


#10

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