[Solved] 3/33 - I did it, but what is wrong with this one?


#1

So I need to print the FizzBuzz game from 1 to 20, okay. I spent a good time with this code:

for (var i = 1; i < 21; i++) {
    var kk = i;
    switch(kk) {
        case (kk % 3 === 0 && kk % 5 === 0):
            console.log('FizzBuzz');
        break;
        case (kk % 3 === 0 && kk % 5 !== 0): 
            console.log('Fizz');
        break;
        case (kk % 3 !== 0 && kk % 5 === 0):
            console.log('Buzz');
        break;
        default:
            console.log(kk);
    }
   
}

And it didn't work, but when I changed the switch(kk) to switch(true) it worked perfectly. But I can't figure out what is wrong with the first one, can someone help me?


#2

The return type of the cases you are using is boolean (true or false). When you switch by integer like "i" or "kk", you are checking if number is equal to true or false. This is why the code doesn't return the expected result.


#3

Thank you very much!


#4

in addition to what @julietaatanasova has said to make your code work you can try something like this below

for (var i = 1; i < 21; i++) {
    var kk = i;
    var print;
    switch(true) {
        case kk % 3 === 0 && kk % 5 === 0:
           print ='FizzBuzz';
        break;
        case (kk % 3 === 0 && kk % 5 !== 0): 
            print = 'Fizz';
        break;
        case (kk % 3 !== 0 && kk % 5 === 0):
            print = 'Buzz';
        break;
        default:
            print = kk;
    }
    console.log(print);
   
}

#5

It worked in the previous way, just changing to switch(true).

Is there a benefit from doing it this way? Maybe a cleaner code, easier for others to read?


#6

I think that is more readable with if else

var i;
for (i = 1; i <= 20; i++){
    if (i % (3 * 5) === 0){
        console.log('FizzBuzz');
    }
    else if (i % 3 === 0){
        console.log('Fizz');
    }
    else if (i % 5 === 0){
        console.log('Buzz');
    }
    else {
        console.log(i);
    }
}