If (all) else is complicated, switch to switch?

jmdejager

🐤🥇 Jasper de Jager

Posted on April 1, 2021

If (all) else is complicated, switch to switch?

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');
}

Enter fullscreen mode Exit fullscreen mode

It feels hacky and awesome at the same time 😂 Do you think it's worth using?

💖 💪 🙅 🚩
jmdejager
🐤🥇 Jasper de Jager

Posted on April 1, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related