This is a correction to Gumbo's answer. I'm writing a separate answer only because this won't fit as a comment.
Edit: Gumbo suggested in a comment that I may have misread Doug's intention. If the OP really wants both "bye" and "lol" to be printed out for count >= 4, then we need to remove a break
from the switch
. The cases are now back in the original order, so that "bye" and "lol" are printed in that order (which is apparently the OP's intent.)
switch (true) {
case (count == 2):
document.write("hi");
break;
case (count > 3):
document.write("bye");
// No break here; just fall through.
case (count >= 4):
document.write("lol");
break;
}
In this case, I agree with Gumbo that the revised if
statement is correct.
Original answer follows (assumes that the OP really wanted either "lol" or "bye" to print, but not both.)
The switch
statement that Gumbo wrote won't work for count >= 4, for much the same reason that Gumbo's original if
statement won't work: Because the cases are evaluated in sequence, count >= 4 implies that the second case (count > 3) will be executed; so the script will never reach the test for count >= 4. To fix this, the tests should be executed in the reverse order, from highest to lowest:
switch (true) {
case (count >= 4):
document.write("lol");
break;
case (count > 3):
document.write("bye");
break;
case (count == 2):
document.write("hi");
break;
}
The corrected if
statement is still not right either, because for count >= 4 it will produce both bye
and lol
on the output. Again, the tests within the if
ladder should be arranged to go from highest to lowest values:
if (count >= 4) {
document.write("lol");
} else if (count > 3) {
document.write("bye");
} else if (count == 2) {
document.write("hi");
}
This isn't an ideal example, because if count
is an integer, then evaluating count >= 4
and count > 3
will produce the same results -- true
for count >= 4, false
otherwise. That wouldn't be the case if count
is a floating-point value (but then, a floating-point value named "count" would raise other concerns.)