Friday, May 17, 2024
112
rated 0 times [  113] [ 1]  / answers: 1 / hits: 113616  / 15 Years ago, mon, february 22, 2010, 12:00:00
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?


More From » switch-statement

 Answers
9

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

[#97519] Wednesday, February 17, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zainsagez

Total Points: 555
Total Questions: 99
Total Answers: 96

Location: Honduras
Member since Sat, Jul 24, 2021
3 Years ago
;