0

I'm a Swift developer and I run the following switch statement on average which is a Double. I was using this on the iOS side.

// example average = 1.27908341230...

switch average {

case 1.0..<1.5:
    //doSomething
case 0.5..<1.0:
    //doSomething
case 0.0..<0.5:
    //doSomething
default:            
    break
}

Now I'm using the code in Cloud Functions. Is this the correct way to do this in Javascript?

// example average = 1.27908341230...

switch (average) {

case 1.0 < 1.5:
    //doSomething
    break;
case 0.5 < 1.0:
    //doSomething
    break;
case 0.0 < 0.5:
    //doSomething
    break;
default:            
    break;
}
Lance Samaria
  • 17,576
  • 18
  • 108
  • 256

1 Answers1

1

Don't use switch, use if/else.

if (average > 1 && average <= 1.5) {
  // do something
} else if (average > 0.5 && average <= 1) {
  // do something
} else if (average > 0 && average <= 0.5) {
  // do something
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thanks for the answer. I can accept the answer in 12 minutes. Why shouldn't I use `switch`? – Lance Samaria Apr 04 '21 at 18:42
  • 1
    `switch` (1) just doesn't work for what you're trying here (unless you use `switch(true)`, which is weird and ugly) (2) `switch` is verbose (3) `switch` is error-prone (people frequently forget to `break` (4) modern variable declaration syntax can't be used inside a case unless you make it into a block. `if`/`else` is just so much better – CertainPerformance Apr 04 '21 at 18:46
  • ok, thanks for the clarification. I'll accept your answer as soon as it lets me. Cheers!!! – Lance Samaria Apr 04 '21 at 18:47