...And the good! Switch


Hi, everyone!

Tell me, please why if I want to use switch for this task it only prints out list of numbers without Fizz Buzz and FizzBuzz?

Here is the code:

for (i=1; i < 21; i++) {

switch (i) {
case (i%3 === 0):


case (i%5 === 0 ):  


case ((i%3)&&(i%5) === 0 ): 



console.log(i); break;




the only thing that print number is console.log(i);it's mean that each case are null wich is strange if you did well with the "for"


FizzBuzz needs to be on the top but before the for


I think that maybe the problem is that you didn't put any break's after the console.log's.


Switch and case statements don't do conditional tests. It compares the variable to each case, then executes the code on a fall through basis. So any time it hits a matching case, it will execute every statement after, therefore you need the breaks, unless you want to use this fall through - which is regarded as very dodgy practice.

But let's say you are really determined to do FizzBuzz without if statements and make use of switch / case. Here's one way you could do it.

for (i=1; i < 21; i++) {
    var f = i % 15 === 0 ? 15 : i % 3 === 0 ? 3 :  i % 5 === 0 ? 5 : i;
    switch (f) {
        case (3):
            console.log("Fizz"); break;
        case (5):  
            console.log("Buzz"); break;
        case (15): 
            console.log("FizzBuzz"); break;

It's not a great way, the case statement will work, but instead of easier to read and debug if statements, I've put in a hideous stacked ternary operator to determine the value of f based on i.