Just a little piece of awesome code I picked up at work: replacing an if else statement with a switch!
if(someExpressionA){
console.log('yes');
} else if (
someExpressionB && someExpressionC
|| someExpressionD
) {
console.log('nope');
} else {
console.log('maybe');
}
switch(true){
case someExpressionA:
console.log('yes');
break;
case someExpressionB
&& someExpressionC:
case someExpressionD:
console.log('nope');
break;
default:
console.log('maybe');
}
It feels hacky and awesome at the same time 😂 Do you think it's worth using?
Top comments (29)
I think it depends.
If it looks cleaner to you and your team, then that's the answer (use it).
Personally, I have a slight preference to normal if / else statements because:
true
orfalse
. Whereas if / else statements also work with "truthy" or "falsy" values. For exampleif ('hello' && 'goodbye')
passes, because non-empty strings are truthy, butswitch(true) { case 'hello' && 'goodbye': }
wouldn't pass.In summary. It's not my cup of tea. But it's not a big change, so I would do it if that's what the team preferred. If you and your team like it, then by all means use it :).
I totally agree with the first point. If you have truthy and falsy value you should prefer
if
but for long strict conditions,switch
can be preferable.I get what you you're saying only
isn't actually checking anything I guess.
The rest are sure valid points! 😊 thnx for sharing
Fair point lol. Off the top of my head I use them sometimes to check for empty strings and stuff :). No problem, thanks for sharing the tip.
Coincidentally, a friend of mine told me this week his
switch(true)
did not pass his code review, despite the arguments of it looking much clearer. Some people will not accept this, so beware 😛Because anyone who isn't used to seeing it will think it's a typo and then have to rethink what the function is doing.
But what if it is more common. At some point you would expect a turning point if there are no other downsides ofcourse.
Generally I think people are trying to move away from functions that have a lot of conditionals, so it's probably not going to become more common.
good point, not a fan of them myself 😉
hence my question, should I use it 😁
Would like to understand the reason for not allowing
switch
(if you can share). Because. even I have started using switch over if-else in many cases. It just make more sense to me.I think it is because it takes an extra thinking step.
if/else-if is more easily read as a sentence. But please let me know if there are other reasons.
Just a bit of a guess here, but I think the switch statement is considered a last resort when you have a ton of conditionals that can't be done any other way.
The switch statement may be like a logic shortcut when there may be another solution out there. Sometimes if/else is sufficient and reads easier when you really don't have that many statements. Sometimes a quick if like
if (!someExpressionA) { return console.log('yes') }
may be a less intensive solution. And some people just don't like using conditionals at all and prefer to use objects whenever they can.I kinda use all four solutions depending on the situation, so maybe @dantederuwe 's friend didn't pass because there was a better solution. Just a total guess of course!
TBH I've never considered doing this but now that I see it, it feels like an abuse of the switch statement.
Neither example seems particularly "clean" to me.
My preference would be to refactor this code such that you can return early.
Much more straightforward than either IMHO.
Which can, in turn, be simplified by Java 13's Enhanced Switch statement (or even a ternary statement at that point).
Thnx for sharing! Honored to be your first comment 😊😉
I agree, the console.log was purely for the example. I also think most people will agree with you, my first feeling was also that it feels hacky. But... There are people that do use it, so it is good to know it exists 🙂
can use objects like below, looks very clean
Switches have the potential to be super powerful, the ability to let conditions fall through...
...means there are some complex logical flows that could achieved.
But the hidden complexity fall-through case statements add and the ease of missing them means it's far more likely you'll introduce hard to find bugs or regressions.
As a result, most coding styles either warn or actively disallow case statements without a
break;
statement at the end. Removing that ability removes the key differentiator of aswitch
statement and makes it a slightly more conciseif..else if
statement assuming you have a set of conditions checking the same variable for different values. Pretty niche!Little OT here. I think switches are great for revealing unexpected program flows in a multi branch szenario, which is why the exact match condition is so important.
You want your program being as deterministic as possible and therefore throw exceptions when the program deviates at any point. Switches are a nice way to do that:
Relying on truthy/falsy for branching is a great feature of Js but can also lead to false positives / false negatives (think empty Strings, Number 0) that require much more tests than being explicit in the first place.
I agree with your initial point, but not necessarily that switches are the answer.
In your example, I'd probably do something like:
...or more generically assuming things weren't as 1-to-1...
The second is probably the easiest to understand out of all of them (including the switch imo) so I'd probably lean towards that, but in every case, undefined behaviours are caught appropriately.
Sounds like Ramda cond. Thinking about a switch statement in terms of functions might be an interesting new perspective! This stack overflow piece might help.
I think it's worth using. In fact, in the previous enterprise-level project I worked on, 'switch'es were the most prevalent for handling several conditions. If/else's were seldom used.
switch in c# is more clear. I didn't use in javascript