DEV Community

Cover image for Opinionated use of JavaScript Switch-Case
bob.ts
bob.ts

Posted on

Opinionated use of JavaScript Switch-Case

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.

Top comments (3)

Collapse
 
sirseanofloxley profile image
Sean Allin Newell

Wat. I am so intrigued

const someFlag = true;
const name = 'bob'; // or tom

switch (name) {
  case 'bob':
    return someFlag ? 20 : 10;
  case 'tom':
    return 5;
  default:
    return -1;
}
Enter fullscreen mode Exit fullscreen mode

This seems clearer to me, but i can see the flexibility of your way.

Collapse
 
rfornal profile image
bob.ts

I agree that yours might be clearer with a smaller example, but when using something with dozens of variables, it's clear and the flexibility is really nice.

Collapse
 
jkimexploring profile image
JkImExploring

This is really cool! I know I've seen this type of pattern with the empty case before but I haven't explored using it too much yet.