JavaScript Switch/Case Best Practices for Complex Logic Trees

Viewed 118

I've recently been in a code syntax formatting debate and would like to get the opinion of the broader JavaScript community. I personally prefer this switch/case structure for complicated condition trees but other developers seem to dislike it. Below I will post my preferred switch/case structure and the if/else equivalents.

Rather than debate preferences, why is this switch/case code acceptable or unacceptable and the specific reasons? If the other alternatives are better, why?

// My preferred switch/case block

switch (true) {
  case testA()              : return 'A';
  case testB() || testG()   : return 'B';
  case testC()              : return 'C';
  case testA() && !testB()  : return 'ZETA';
  case a === b && c !== d   : return 'foo';
  default                   : return 'bar';
}

// if-else alternate #1

if (testA()) {
  return 'A';
}
if (testB() || testG()) {
  return 'B';
}
if (testC()) {
  return 'C';
}
if (testA() && !testB()) {
  return 'ZETA';
}
if (a === b && c !== d) {
  return 'foo';
}
return 'bar';

// if-else alternate #2

if (testA())               return 'A';
if (testB() || testG())    return 'B';
if (testC())               return 'C';
if (testA() && !testB())   return 'ZETA';
if (a === b && c !== d)    return 'foo';
return 'bar';
1 Answers

once you remove the else from the alternative #1 now you have is an alternative #2, just with extra artifacts and lines.


It is all about style; what is easier to Read and easier to Refactor in the case of logic needs to be updated. It all depends on your use case and intention when writing the code.

Personally, I prefer a good and simple Switch-Case statement over lines of nested If-Else logic. All the time I see those If(){} Else If(){} I want to scream in pain and run away from that code.

In this case, Alternative #3 is clean, compact, easier to read and refactor. I can see quickly on this example logic will require to be refactored, and the Switch-Case statement can require more work than the simple If solution.

Related