-1
\$\begingroup\$

I was just tempted to write a similar piece of code to the one presented in this answer on SO (posted below). The problem is having to discriminate between different cases where exactly one case is true.

In my experience switch statements are usually use to match the value of an expression against various constants. But in this case we use a switch statement to decide which of the conditions is true. To do this I would actually prefer using if/else if because switch(true) feels a little bit like an abuse of switch, but this is just a gut feeling. On the other hand I think this piece of code is still prefectly readable even with its seemingly unconventional use of a switch statement.

Are there any objective reasons why one would prefer switch over if/else if or vice versa when it comes to code quality, performance and readability?

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

  //etc...
\$\endgroup\$
2
0
\$\begingroup\$

Not really a review question. But as this will be closed I might as well give a quick answer. You should have asked this at SO.

switch statement are meant as a shortcut to long lists of simple if (a == 1) else if (a == 2) else if (.... They ended up in JS as that is what was needed to attract C/C++ coders to the language back in the day when JS was SLOW.

There is nothing wrong with using them but in most cases you can simplify with if else.

EG

// 3 logic operations
if (a >= 75) {   // 1
   if (a < 100) { ... } // 2 
   else if (a < 150) {/* 3 logic operations to get here */}  // 3
}

// 8 logic operations
switch (true) {  // this must evaluate on each case === true if you get to them
  case (a >= 75 && a < 100): //  1:(a >= 75)  2:(a < 100) 3:(&&) 4:(case === true)
    ...
    break;
  case (a >= 100 && a < 150): //  5:(a >= 100)  6:(a < 150) 7:(&&) 8:(case === true)
    /* 8 logic operations to get here */
    break;
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.