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?
When
switchis interpreted, the expression in the parentheses is compared to values of the particular cases.So in your case the value of
countwould be compared to the values of2,count > 3andcount >= 4. And that won’t work. Although you can rewrite it and compare totrueto get it working:But that’s not how
switchis supposed to be used.Use
ifstatements instead:Edit Since you use the
switchcases exclusively (break if a case matches), myswitch-to-if/elsetranslation is correct.But the
count >= 4case/branch will never be applied sincecount > 3is true (also) forcountvalues greater or equal 4.To fix this problem (write “bye” and “lol” for values greater or equal 4), remove the last
elseto make the lastifstatement independent from the preceding: