3....and the good! Can't make it log correctly


#1
  1. ...and the good!

"You printed 3 when you should've printed "Fizz". It will print out numbers 1-20, like it's just going to default every time. I can't get it to go to my "case" sections. Usually I find something simple that is wrong with it after a couple minutes, but I can't seem to figure this one out.

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

#2

I changed my code to an if/else format, but didn't alter the rest of the code and it worked. So, I completed the exercise, but would still like to figure out what was going on here, for learning purposes. Thanks!


#3

Hey there,

Interesting, I used ifs and if elses but a switch statement will work. However there's one problem.

When you think about it switch is asking the cases whether the condition in it's parentheses is equal to the cases result. Let's put this in plain context:

is switch(3) equal to the second case which evaluates to true? Well we have no way of telling this because we can't possibly say that 3 is equal to true. So lets move on, until eventually nothing is left and it just defaults to printing out the i value.

So instead what we would like to do is use switch(true). Because now we can test if true is equal to the result of the case conditionals.

is switch(true) equal to the first case which evaluates to false. Actually no it's not. But the second case is equal to true. So let's do that instead and move on to the next iteration of i.

I really hope that makes sense to you :slight_smile:


#4

Yes, that completely makes sense! I was looking at switch() as an input and each case as a "true" or "false", not as verification. Thank You!


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.