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.
Top comments (3)
Wat. I am so intrigued
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.