...And the good! Switch


#1

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):

    console.log("Fizz");

case (i%5 === 0 ):  

    console.log("Buzz");

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

    console.log("FizzBuzz");

default: 

console.log(i); break;

}

};


#2

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"


#3

FizzBuzz needs to be on the top but before the for


#4

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


#5

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;
        
        default: 
            console.log(f);
    }
}

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.