JavaScript Tip: Checking Multiple Cases in a Switch Statement

I recently worked on a JavaScript function that used a switch statement to branch the logic based on a certain value, but each action applied to multiple different cases. It would be overkill to repeat the same logic in multiple case statements. Fortunately, JavaScript can handle this, although the structure of the code might not be what you’d expect.

My instinct is to try something like this:

switch (myVariable)
{
  case "A", "B", "C":
    // Do something
    break;
  case "D", "E":
    // Do something else
    break;
  default: 
    // Default case
    break;
}

But that doesn’t work.

The correct syntax makes use of the ‘fall-through’ behavior of the JavaScript switch statement. Once it matches a case, it will keep executing code until it either hits a break statement or the end of the switch.

This code will do the trick:

switch (myVariable)
{
  case "A":
  case "B":
  case "C": 
    // Do something
    break;
  case "D":
  case "E":
    // Do something else
    break;
  default: 
    // Default case
    break;
}

In this example, if the value of myVariable is A, B, or C, it will execute the code under case "C":.

Advertisements

One response to “JavaScript Tip: Checking Multiple Cases in a Switch Statement”

  1. edm00se says :

    I had run into the same thing before, though I attempted to use an or on my values. Thankfully, Mozilla Developer Network set me straight. Your solution is in perfect keeping with their example.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch#Examples

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: