DEV Community

Cover image for Opinionated use of JavaScript Switch-Case

Opinionated use of JavaScript Switch-Case

REAL, FUN, GEEK who is passionate about Front-End!
・1 min read

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):
  case (time=== true):
  case default:
Enter fullscreen mode Exit fullscreen mode

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


... 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.

Discussion (3)

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;
    return -1;

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

rfornal profile image
bob.js Author

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.

jennakoslowski profile image

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.