DEV Community

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

Posted on • Originally published at calvintorra.com

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

Top comments (0)