loading...
Cover image for Opinionated use of JavaScript Switch-Case

Opinionated use of JavaScript Switch-Case

rfornal profile image bob.js ・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):
    console.log('person');
    break;
  case (time=== true):
    console.log('time');
    break;
  case default:
    console.log('other');
    break;
}

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.

Posted on by:

rfornal profile

bob.js

@rfornal

REAL, FUN, GEEK who is passionate about Front-End!

Discussion

markdown guide
 

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;
}

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

 

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.

 

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.