Is there a way to write a conditional switch statement in JavaScript?
I’m guessing not, since the following is always going to default:
var raw_value = 11.0;
switch(raw_value)
{
case (raw_value > 10.0):
height = 48;
width = 36;
break;
case (raw_value > 5.0):
height = 40;
width = 30;
break;
default:
height = 16;
width = 12;
break;
}
If not, what should I use instead – a long if/else statement?
In a
switchstatement, the evaluated value of theswitchexpression is compared the the evaluated values of the cases. So here the value ofraw_value(number) is compared toraw_value > 10.0(comparison expression) andraw_value > 5.0(comparison expression).So unless one of your case expressions yield a number equal to
11.0or you use theswitchexpressiontrue, you will always get the default case.Just use a simple
if/elseinstead: