DEV Community

Discussion on: Using the Switch Statement with Logical Operators

Collapse
 
xowap profile image
Rémy 🤖

What is the advantage of this syntax over if/elseif?

Collapse
 
jasterix profile image
Jasterix • Edited

I decided to use it here to get more practice with switch statements, but in this scenario, if/else would be more appropriate

this article explores when to use if/else vs a switch statement

Collapse
 
porobertdev profile image
Robert P.

Adding to this, MDN's article linked from The Odin Project says that one of the cases switch should be used over if...else blocks is when you have to deal with many choices.

Thank you for the article! I didn't understand why logical operators doesn't work for switch.

Thread Thread
 
codepioneer2 profile image
CodePioneer2

I think you are missing the point of switch statements totally.
If you think about this code:
if (a > 3)
else if (a > 2)
else if (a > -3)
else ...

there is no point writing it many times because every expression is using the same variable 'a'. You take the 'a' and put it to switch handler

switch(a)....
case 3:
...
case 2:
....
case -3:
default:
....

Thread Thread
 
porobertdev profile image
Robert P.

Yes, you're correct. I might have not explained properly back then, but I believe that's what I wanted to say as the MDN article I have referenced says exactly what you said.

Fast forward to today, I barely have used the switch statement in the past 1.5 years. I have two cases at the most in general, so I go with ternary especially in the functional components.

I think a switch case with 3-4+ cases (or multiple ifs ) can be a sign to refactor the code.