DEV Community

Cover image for How To: if statements in Javascript Switch case?
Calvin Torra
Calvin Torra

Posted on • Originally published at calvintorra.com

1 1

How To: if statements in Javascript Switch case?

Original Post and more here

A situation came up where I had to check for keyboard events and I wanted to include WASD as well as the arrow keys.

I decided on a switch statement but ended up having 8 cases and only 4 outcomes that I actually wanted to happen.

Then I wondered if it was possible to use and if statement in a switch case….turns out it’s better to use a fall through pattern.

Here’s a basic set up of what I would have had to do.

switch(value){
  case 'ArrowUp':
  // do 3 things
  break
  case 'KeyW':
  // do 3 things
  break
  case 'ArrowDown':
  // do 3 things
  break
  case 'KeyS':
  // do 3 things
  break
  // and more
}
Enter fullscreen mode Exit fullscreen mode

Here is the “fall through” method. I know I had seen this before, but I’ve never used it out in the wild, so here it is to remind my future self.

We can simply specify several cases that we want to watch for, bunch them all up together and give a single outcome.

In the case below, I want to check if the value is Either the ‘ArrowUp’ key OR the ‘KeyW’ key. If either of those two occur, they’ll be treated the same.

switch(value){
  case 'ArrowUp':
  case 'KeyW':
  // do those things
  break
  case 'ArrowDown':
  case 'KeyS':
  // do those things
  break
}
Enter fullscreen mode Exit fullscreen mode

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay