Switch statement multiple cases in JavaScript

Afshin Mehrabani picture Afshin Mehrabani · Nov 3, 2012 · Viewed 712.8k times · Source

I need multiple cases in switch statement in JavaScript, Something like:

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

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

How can I do that? If there's no way to do something like that in JavaScript, I want to know an alternative solution that also follows the DRY concept.

Answer

kennytm picture kennytm · Nov 3, 2012

Use the fall-through feature of the switch statement. A matched case will run until a break (or the end of the switch statement) is found, so you could write it like:

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

   default: 
       alert('Default case');
}