JavaScript switch with logical operators?

Viewed 104236
for (var count = 1; count < 6; count++) {
    switch (count) {
        case (2):   document.write("hi"); break;     
        case (count > 3):   document.write("bye"); break;    
        case (count >= 4): document.write("lol"); break;
    }
}

Because it's not working the way I expect, not printing bye and lol, it makes me think this is invalid in JavaScript. I tried looking for some examples to see if people do this on Google, and I saw none. So is this valid or not? or Why might this not work?

5 Answers

When switch is interpreted, the expression in the parentheses is compared to values of the particular cases.

So in your case the value of count would be compared to the values of 2, count > 3 and count >= 4. And that won’t work. Although you can rewrite it and compare to true to get it working:

switch (true) {
    case (count == 2):
        document.write("hi");
        break;
    case (count > 3):
        document.write("bye");
        break;
    case (count >= 4):
        document.write("lol");
        break;
}

But that’s not how switch is supposed to be used.

Use if statements instead:

if (count == 2) {
    document.write("hi");
} else if (count > 3) {
    document.write("bye");
} else if (count >= 4) {
    document.write("lol");
}

Edit    Since you use the switch cases exclusively (break if a case matches), my switch-to-if/else translation is correct.

But the count >= 4 case/branch will never be applied since count > 3 is true (also) for count values greater or equal 4.

To fix this problem (write “bye” and “lol” for values greater or equal 4), remove the last else to make the last if statement independent from the preceding:

if (count == 2) {
    document.write("hi");
} else if (count > 3) {
    document.write("bye");
}
if (count >= 4) {
    document.write("lol");
}

You use the case clause in the wrong way. You should provide a value that will be compared to the value in the switch clause ... and not a boolean expression like this count>2

In this case this boolean expression will be cast to true or false (1 or 0) and compared to your value count and sometimes may work, sometimes - not.

You should consider replacing it with if statements.

The switch normally needs a fixed condition/value; because your count variable changes every time, it goes against that. Use if-else condition instead.

You should swap your last two cases.

Related