JavaScript switch with logical operators?

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");
}

Leave a Comment