# Question about the order

#1

Before i altered the code to be like it is below; my first attempt was putting (i % 3 === 0) and then i% 5 === 0) and last of all (i % 3 === 0 && i % 5 === 0). However then it would not print out fizzbuzz only fizz and buzz, why is this?

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

#2

Well, with the "if - else if" type of construct you go from the top to bottom entering the first statement with a fulfilled condition. You then skip the rest. So you will need to put the statement with the strictest condition on the top.

#3

If the first condtion test is not the combined expression, then it will never be true since either i % 3 or i % 5 will have already passed and jumped out of the if statement back into normal flow. Consequently, `FizzBuzz` will never print.

Aside

This is an example of an LCM problem. What is the least common multiple of 3 and 5? That would be their product, 3 * 5 => 15.

``````if (i % 15) {
console.log("FizzBuzz");
}``````

This would still need to be the first conditional in the statement, but it simplifies the logic.

#4

@mafecardozo7

``````program
flow
|
V                                                - - - -
for(var i=1;i<21;i++){ - - - - - i >= 21 - - - - - -> | EXIT |
|            |                                           - - - -
^            V
|         (i < 21)
^            V
|           if (i%3===0 && i%5 ===0 ){
|                console.log("FizzBuzz"); - - - > - - - -+
|           }                                            |
^           else if (i%5===0){                           V
|                console.log("Buzz"); - - - ->- - - - - -+
|           }                                            |
^           else if (i%3===0 ) {                         V
|                console.log("Fizz"); - - - -> - - - - - +
|           }                                            |
|           else {                                       V
|                console.log(i); - - - - - - - - -> - - -+
|           }                                            |
^ - - - - - -< - - - - - - < - - - < - - - - - < - - - - +
}``````

#5

Thank you very much for your replies, makes perfect sense now !