Problem
In JavaScript, I require numerous cases in a switch statement, such as:
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.
Asked by Afshin Mehrabani
Solution #1
Use the switch statement’s fall-through feature. You may express it like this: A matched case will run until a break (or the end of the switch statement) is discovered.
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
}
Answered by kennytm
Solution #2
This is how it works in standard JavaScript:
function theTest(val) {
var answer = "";
switch( val ) {
case 1: case 2: case 3:
answer = "Low";
break;
case 4: case 5: case 6:
answer = "Mid";
break;
case 7: case 8: case 9:
answer = "High";
break;
default:
answer = "Massive or Tiny?";
}
return answer;
}
theTest(9);
Answered by Rob Welan
Solution #3
Here’s a second way that doesn’t use the switch statement at all:
var cases = {
afshin: function() { alert('hey'); },
_default: function() { alert('default'); }
};
cases.larry = cases.saeed = cases.afshin;
cases[ varName ] ? cases[ varName ]() : cases._default();
Answered by elclanrs
Solution #4
To assign several cases in a switch in Javascript, we must declare each case separately without a break in between, as seen below:
<script>
function checkHere(varName){
switch (varName)
{
case "saeed":
case "larry":
case "afshin":
alert('Hey');
break;
case "ss":
alert('ss');
break;
default:
alert('Default case');
break;
}
}
</script>
Click on the link to see an example.
Answered by Er. Anurag Jain
Solution #5
I like this for clarity and a DRY syntax.
varName = "larry";
switch (true)
{
case ["afshin", "saeed", "larry"].includes(varName) :
alert('Hey');
break;
default:
alert('Default case');
}
Answered by Kyle Dudley
Post is based on https://stackoverflow.com/questions/13207927/switch-statement-for-multiple-cases-in-javascript