Passionate about building great technology and connecting with people to create positive change. Happy to answer questions about transitioning to tech. Find me on Twitter @lounecl
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.
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
What is the advantage of this syntax over
if
/elseif
?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
Adding to this, MDN's article linked from The Odin Project says that one of the cases
switch
should be used overif...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
.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:
....
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.