DEV Community

Discussion on: If (all) else is complicated, switch to switch?

Collapse
 
sargalias profile image
Spyros Argalias

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:

  • in JavaScript (the language I use at work), the switch statement wouldn't work unless each expression was explicitly true or false. Whereas if / else statements also work with "truthy" or "falsy" values. For example if ('hello' && 'goodbye') passes, because non-empty strings are truthy, but switch(true) { case 'hello' && 'goodbye': } wouldn't pass.
  • I'm not used to using switch statements like that, so they might catch me out until I get used to them (and others too). If they were the standard convention, then it wouldn't be a problem. As they say, convention over perfection, although this is a very small change in this case.
  • More realistically, I don't encounter long conditionals often. Short conditionals don't seem like a great use case for switch statements. For example:
if (!condition) {
  return foo();
}
return bar();
Enter fullscreen mode Exit fullscreen mode

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 :).

Collapse
 
jmdejager profile image
🐤🥇 Jasper de Jager • Edited

I get what you you're saying only

if ('hello' && 'goodbye')

isn't actually checking anything I guess.
The rest are sure valid points! 😊 thnx for sharing

Collapse
 
sargalias profile image
Spyros Argalias

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.

Collapse
 
hey_yogini profile image
Yogini Bende

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.