Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a switch comparator in JS?

is there a way to create a switch comparator like this one?

switch (item) {
    case (item<= 10):
        money += 25;
        $('#money').html(money);
        break;
    case (item > 10 && item <= 20):
        money += 50;
        $('#money').html(money);
        break;
}
like image 852
Snip3r_now Avatar asked May 05 '15 08:05

Snip3r_now


2 Answers

may be this:

 item = YourValue;
 switch (true) {

        case (item <= 10):
            money += 25;
            $('#money').html(money);
            break;
        case (item > 10 && item <= 20):
            money += 50;
            $('#money').html(money);
            break; 
     }

The expressions in the case statements will evaluate to true or false, and if that matches the switch condition,

but as per my suggestion you should go with if...else if...else statement for this kind of business logic.

like image 120
Mr. Go Avatar answered Oct 02 '22 22:10

Mr. Go


Simple answer: No. Switch..case statements don't work like this. You would need an if & else if statement:

if (item <= 10)
{
    money += 25;
    $('#money').html(money);
}
else if (item > 10 && item <= 20)
{
    money += 50;
    $('#money').html(money);
}
like image 39
bytecode77 Avatar answered Oct 02 '22 21:10

bytecode77