How can I handle multiple cases in a JavaScript switch statement?

I need to check multiple cases in a JavaScript switch multiple case statement, something like this:

switch (varName) {
   case "afshin", "saeed", "larry":
       alert('Hey');
       break;

   default:
       alert('Default case');
       break;
}

Is there a way to handle multiple cases in a single switch statement like this in JavaScript? If not, what’s the best alternative solution that follows the DRY (Don’t Repeat Yourself) concept?

I’ve been working with JavaScript for over a decade now, and the classic way still holds strong for many use cases.

You can stack multiple case labels like this:

switch (varName) {
  case "afshin":
  case "saeed":
  case "larry":
    alert("Hey");
    break;
  default:
    alert("Default case");
}

This is the official way to implement a javascript switch multiple case setup. Each case just falls through until it hits the shared logic. It’s clean, avoids duplication, and great for situations where the action is the same for multiple values.

Been in frontend for 7+ years now, and I’ve grown to prefer cleaner expressions whenever possible, especially when the logic isn’t tightly bound to switch syntax.

If you’re not married to the switch block, this is an elegant alternative:

if (["afshin", "saeed", "larry"].includes(varName)) {
  alert("Hey");
} else {
  alert("Default case");
}

Using includes() on an array keeps the code concise and easy to expand. It’s super DRY and often clearer to read, especially when your javascript switch multiple case check just needs to match values with the same outcome.

Coming from a backend-heavy background, I usually lean into objects or maps for flexibility. Been coding for 9+ years, and this one’s served me well.

For something even more scalable, try using a key-value approach:

const actions = {
  afshin: () => alert("Hey"),
  saeed: () => alert("Hey"),
  larry: () => alert("Hey"),
};

(actions[varName] || (() => alert("Default case")))();

This setup moves you away from switch syntax but keeps the spirit of a javascript switch multiple case structure. It’s especially powerful when each case needs a different action. Plus, it’s neat, extensible, and much easier to maintain as your logic grows.