Opinionated use of JavaScript Switch-Case

bob.ts - Aug 10 '20 - - Dev Community

The Idea

Having just read the Basics of switch cases and defaults, I am reminded of a group code-review I did years ago where I included a switch case-statement in my front end code.

The Code

I would also like to point out that one of our back-end developers (.NET) tried the same pattern and found that it worked, much to his surprise.

This is not the code, but exemplifies what I did ...

const bob = true;
const tom = false;
const time = false;

switch (true) {
  case (bob === true):
  case (tom === true):
    console.log('person');
    break;
  case (time=== true):
    console.log('time');
    break;
  case default:
    console.log('other');
    break;
}
Enter fullscreen mode Exit fullscreen mode

Granted with this code, we don't know which is true (bob or tom) without additional testing, but ...

Conclusion

... using the switch (true) like this gives us a great visible pattern that is not dependent on any single variable.

I'm not saying this is for everyone, but I personally think this is a very clear pattern.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player