HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Switch statement for multiple cases in JavaScript

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
statementformultiplecasesswitchjavascript

Problem

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.

Solution

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');
}

Code Snippets

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

   default: 
       alert('Default case');
}

Context

Stack Overflow Q#13207927, score: 2528

Revisions (0)

No revisions yet.