3/33.. and the good!


#1

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

after running this the code doesnt print FizzBuzz for number divisible by bith 3& 5


#2

Given that this conditional is third in the order of evaluation, what is the chance it will be even seen when i % 3 === 0 or i % 5 === 0? Answer? Zero. None. Zilch. Why? Because 3 and 5 have already tripped their own branch. The statement is finished before it gets to this condition.

Order matters. Test for both first, then each individually, and default to none. That way, you actually do print FizzBuzz.


#3

If you are in any way mathematically inclined, think LCM. This same problem comes up in an earlier lesson in a slightly different form, but it is the same problem, just the same.

function quarter(n){
    return n / 4;
}
if (quarter(12) % 3 === 0) {
    return true;
} else {
    return false;
}

or some such thing. The exercise insisted upon a true result so we were forced to come up with a number that was both divisible by 3 and by 4. Easy answer, 3 times 4. 12. The LCM of 3 and 4.

Any number, 0, 12, 24, ... n * 3 * 4, will satisfy a true condition.

This suggests that we can apply an LCM approach to our FizzBuzz problem that will simplify the program.

if ( i % 15 === 0) {
    console.log('FizzBuzz')
} ...

Compound conditional gone. Make this first in line and everything works as expected.