0

I'm just wondering if there's a way to make this sort of thing work in a switch statement, I'm aware that it's very possible in an else if statement but I would prefer to go with a switch statement, below I've attached an example piece of code to show what I mean...

let money = 42;

switch (money) {
  case < 10:
    console.log('You have $10 or less USD');
    break;
  case < 50:
    console.log('You have $50 or less USD');
    break;
  case < 100:
    console.log('You have $100 or less USD');
    break;
  default:
    console.log('You are rich! Over $100);
    break;
}

if this worked the way I wanted it would print "You have $50 or less USD" as money is < 50 but > 10.

Thanks in advance, Lachie.

StanLachie
  • 57
  • 2
  • 7
  • 1
    [Review the syntax for `switch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch). What you've written is not the correct way to use `switch`. You should probably use `if`/`else` here instead. – VLAZ Jul 28 '21 at 13:35
  • 1
    Not with `switch`, no. `switch` always compares exact values. You have to go `if(money<10){ ... } else if(money < 50) { ... } else if(money < 100){ ... } else { ... }` – Jeremy Thille Jul 28 '21 at 13:36
  • You can make switch work this way, but an if/else if makes more sense.... – epascarello Jul 28 '21 at 13:45

2 Answers2

3

There's actually a nice way to do that, notice that switch(true) will evaluate each expression. Not always readable, but nice to know.

const money = 200;

switch (true) {
  case money < 10:
    console.log('You have $10 or less USD');
    break;
  case money < 50:
    console.log('You have $50 or less USD');
    break;
  case money < 100:
    console.log('You have $100 or less USD');
    break;
  default:
    console.log('You are rich! Over $100');
    break;
}
MorKadosh
  • 5,846
  • 3
  • 25
  • 37
0

const run = (money) => {
  switch (true) {
    case money < 10:
      console.log('You have $10 or less USD');
      break;
    case money < 50:
      console.log('You have $50 or less USD');
      break;
    case money < 100:
      console.log('You have $100 or less USD');
      break;
    default:
      console.log('You are rich! Over $100');
      break;
  }
};

run(42);
run(55);
run(123);

You need to do the comparison with the money that you have.

Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26