How to create a comparator switch in JS?

Is there a way to create a comparator switch like this?

switch (item) { case (item<= 10): money += 25; $('#money').html(money); break; case (item > 10 && item <= 20): money += 50; $('#money').html(money); break; } 
+5
source share
3 answers

may be as follows:

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

Expressions in case statements will be evaluated as true or false, and if this matches the switch condition,

but at my suggestion you should go with if ... else if ... else for this business logic.

+2
source

The simple answer is no. Switch..case statements do not work like this. You will need an if and else if statement:

 if (item <= 10) { money += 25; $('#money').html(money); } else if (item > 10 && item <= 20) { money += 50; $('#money').html(money); } 
+2
source

You can use if else instead of switch

 if (item <= 10) { money += 25; $('#money').html(money); } else if (item > 10 && item <= 20) { money += 50; $('#money').html(money); } 
+2
source

All Articles