Can you help me understand 3/33, please?


#1

For some reason, the following results in error:

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);
    }
}

Whereas, the following doesnt:

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);
    }
}

The only thing that is different is swapping around the divisible by 3 AND divisible by 5 so that it goes at the top.

Why does one work but not the other?


#2

I don't have a definite answer for you but I remember hitting a similar issue. I'm pretty sure all it boils down to is the order in which the code is executed. When the logical operator has been placed at the bottom the first two expressions have already been evaluated and thus dismisses the FizzBuzz output.. If you catch my drift


#3

In other words, check the LCM first, then the individual factors following that, then default, in this order.

if (i % 15 === 0) {
    // 'FizzBuzz'
} else
if (i % 3 === 0) {
    // 'Fizz'
} else
if (i % 5 === 0) {
    // 'Buzz'
} else {
    // i
}