views:

98

answers:

4

Hi everyone,

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

+3  A: 

That is not how a switch block works. The case is used to hold a single value that if they are equal to the value on the switch line. if-else statements will serve you well.

Here is some information about the switch block.

http://www.w3schools.com/js/js_switch.asp

Daniel A. White
Thanks - will accept in 8 minutes when I'm allowed.
Marko
+1  A: 

Firstly, that's not how switch works. You have to specify constants for each case, and those constants will be compared to the expression in parentheses (in your case, amount). That is how switch works, period.

Secondly, switch is not faster than several ifs

And thirdly, you shouldn't really worry about miniscule performance optimizations when you're dealing with javascript.

Fyodor Soikin
+2  A: 

You could always do

switch (true) {
  case (amount >= 7500 && amount < 10000):
    //code
    break;
  case (amount >= 10000 && amount < 15000):
    //code
    break;

  //etc...

It works because true is a constant, so the code under the first case statement with an expression that evaluates to true will be executed.

It's kinda "tricky" I guess, but I see nothing wrong with using it. A simple if/else statement would probably be more concise, and you'd not have to worry about accidental fall-through. But there it is anyway.

MooGoo
A: 

A shorter but may be less readable alternative could be using the ternary operator:

function reward(amount) {
    $('#reward').text = 
         (amount >= 7500 && amount < 10000) 
              ? "Play Station 3"
       : (amount >= 10000 && amount < 15000)
              ? "XBOX 360"
       : (amount >= 15000)
              ? "iMac"
       : "No reward";
}
KooiInc