I’m trying to create a switch statement but I can’t seem to be able to use an expression that gets evaluated (rather than a set string/integer). I can easily do this with if statements but case should hopefully be faster.
I’m trying the following
function reward(amount) {
var $reward = $("#reward");
switch (amount) {
case (amount >= 7500 && amount < 10000):
$reward.text("Play Station 3");
break;
case (amount >= 10000 && amount < 15000):
$reward.text("XBOX 360");
break;
case (amount >= 15000):
$reward.text("iMac");
break;
default:
$reward.text("No reward");
break;
}
}
Am i missing something obvious or is this not possible? Google hasn’t been friendly in this case.
Any help/pointers appreciated
M
amountis a number, but the expressions in thecaseclauses only evaluate to booleans; the values will never match.You could always do
It works because the value being matched is now the boolean
true, so the code under the firstcaseclause with an expression that evaluates totruewill be executed.It’s kinda “tricky”, I guess, but I see nothing wrong with using it. A simple
if–elsestatement would probably be more concise, and you’d not have to worry about accidental fall-through. But there it is anyway.