Switch statement for multiple cases in JavaScript
Asked Answered
A

26

1190

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.

Aenneea answered 3/11, 2012 at 9:43 Comment(2)
Sad that this syntax is not working :(Rees
the syntax is valid but it will only check on the last case, javascript should throw an error in such a caseWobbling
R
2426

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');
}
Rissa answered 3/11, 2012 at 9:44 Comment(10)
See: developer.mozilla.org/en-US/docs/JavaScript/Reference/…Priapitis
Somehow it works for me in Chrome, in the javascript console: switch('10') { case 1, '10': console.log('ok') } prints okTrifocal
@nafg: Try switch(1). The label here is just a comma expression.Rissa
Isn't break at the every end of the statement redundant?Zolnay
@Zolnay No, without the break you can fall through to the next case.Tao
@Seiyira by definition, there is no next case after the last. Besides, it's a default.Zolnay
@Zolnay I suspect the confusion is because you said "every" when you meant "very". I also read it as "the end of every statement" at firstChanda
(And yes, the break in the default case is redundant)Chanda
@Chanda yes in this case is redundant, but remember that the default label could not be the last one, so be aware.Rennie
@NetoYo true, I was just trying to be more specific, but I realize it was ambiguous, I should have said "last". Also, personally I wouldn't have edited the break out of the answer as I think it's a matter of personal preference - a lot of people would advocate including a break on every case, even default, and I suspect kennytm knew what he intended.Chanda
P
165

This works in regular 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);
Penetrant answered 17/1, 2016 at 2:15 Comment(7)
@believesInSanta it's literally just normal case fallthrough with weird formatting (spaces instead of newlines)Venosity
You also can use case (1||2||3): instead of case 1: case 2: case 3:Bellybutton
case 1: case 2: case 3: worked for me and thanks, but @kasun Your solution does'nt work.Engdahl
just an fyi, I tried @Kasun's method in TS, and it didn't work for me (I'm aware that OP wanted the solution in JS)Stockwell
The reason why @KasunHasanga's suggested solution doesn't work is because case (1||2||3): is equivalent to case 1: (since 1||2||3 evaluates to 1).Betteanne
@KasunHasanga case (1||2||3): doesn't work.Plumate
@MihailMalostanidis This allows you to reduce duplication if your code for several cases is the same value.Boraginaceous
T
49

Here's different approach avoiding the switch statement altogether:

var cases = {
  afshin: function() { alert('hey'); },
  _default: function() { alert('default'); }
};
cases.larry = cases.saeed = cases.afshin;

cases[ varName ] ? cases[ varName ]() : cases._default();
Trella answered 3/11, 2012 at 9:55 Comment(11)
I definitely prefer this version. Fall through is a bug-prone feature of switch ... case. It's too easy to forget a break statement, and if you use fall through intentionally, those forgotten break statements can be very hard to spot. This method lookup version also has lots of great features that switch ... case lacks, such as dynamic extensibility, or the ability to completely replace the object to accomplish mode switching. It's also easier to keep cleanly organized, and can lead to more maintainable code. See ericleads.com/2012/12/switch-case-considered-harmfulPectoralis
I always add a comment //fallthrough in place of break whenever I intentionally omit the break. That helps to identify when it's a mistake and when it's intentional.Antonomasia
Intuitive approach. However, for readability, I'd recommend to use the native switch statement.Dickinson
One can always scratch the left ear passing its right hand through the back of the neck... (sorry for my english, I mean: "one can always complicate things as much as possible...in this case, avoiding the switch statement in favor of this complicated solution doesn't seem to be the right thing to do...)Ptolemaeus
Nah, switch is antipattern in my book. This is not complicated at all, on the contrary, it is a common alternative, and obviously better for maintainability and refactoring, as you can now move the cases around, because you got expressions, not statements.Trella
@ClintEastwood I would agree except for the fact that I often like to abstract away the actions to be taken. If I'm wrapping a bunch of handlers for someone else to use, it's nice to give them a bunch of labelled functions: they don't need to look at the functions at all, just apply the correct one based on the label.Step
I'm truly amazed how this has gotten 34 up votes. In terms of readability and maintainability, this is absolutely horrific. If I want to see what conditions will trigger something, a case statement is incredibly simple and easy to see by looking at the labels. On the other hand, your version would require someone read pretty much every single line and see what you assigned where. This also gets even worse the more cases you want to match.Tiossem
@Tiossem It was posted a long time ago on a question linked to from MDN. Of course it's got upvotes. :-/Barnie
This is terrible if the only reason you are doing this is because you have a phobia to switch statements. I would be pissed if I had to read this just to figure out it was the same as a switch. KISSCorpuscle
This is a horrible function. How is a junior developer supposed to quickly look at this and understand it? Yes, a switch statement takes up more space, but it is easier to debug and maintain.Archeozoic
(cases[varName] || cases._default)():Kristin
S
35

In Javascript to assign multiple cases in a switch, we have to define different case without break inbetween like given 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>

Please see example click on link

Supra answered 3/11, 2012 at 9:53 Comment(1)
It's a common technique in a pletora of languages, not bound to JSUnderproof
P
31

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

}
Polymerism answered 4/2, 2020 at 0:16 Comment(2)
This is just an over-complicated if-conditionCoward
instead of if (true) you're saying if ("true" == "true")Desperate
K
24

If you're using ES6, you can do this:

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

Or for earlier versions of JavaScript, you can do this:

if (['afshin', 'saeed', 'larry'].indexOf(varName) !== -1) {
   alert('Hey');
} else {
   alert('Default case');
}

Note that includes won't work in some browser including older IE versions, but you could patch things up fairly easily. See the question determine if string is in list in javascript for more information.

Kristin answered 30/7, 2013 at 20:11 Comment(6)
What is the benefit of this over a switch?Ardenardency
@BryceSnyder the difference between an expression and a statement? Less typing? Fewer vertical lines consumed? Greater expressive power through succinctness and density of representation? Better semantics through the includes word? Take your pick.Kristin
The benefit for me is, i can use the array from an external config source and after the array is changed externally the code still works.Portcullis
This is my preferred option, these blocks of case options seem crazy, includes can use the original array instead of extracting elements individually.Drawtube
This is a pretty reliable option, the only drawback is that it isn't as readable as a switch statement.Jamey
@AndrewKnackstedt It's not really in competition with a switch statement. If you want to enable the eye to scan the items, add a newline before and after them, e.g. if (\n'afshin', 'saeed', 'larry'\n).includes(varName). A switch typically is only needed when there are multiple cases to check for, and using it for just a single case seems mismatched to its purpose.Kristin
P
15

My situation was something akin to:

switch (text) {
  case SOME_CONSTANT || ANOTHER_CONSTANT:
    console.log('Case 1 entered');

  break;

  case THIRD_CONSTANT || FINAL_CONSTANT:
    console.log('Case 2 entered');

  break;

  default:
    console.log('Default entered');
}

The default case always entered. If you're running into a similar multi-case switch statement issue, you're looking for this:

switch (text) {
  case SOME_CONSTANT:
  case ANOTHER_CONSTANT:
    console.log('Case 1 entered');

  break;

  case THIRD_CONSTANT:
  case FINAL_CONSTANT:
    console.log('Case 2 entered');

  break;

  default:
    console.log('Default entered');
}
Pursley answered 7/1, 2020 at 13:46 Comment(0)
H
10

Adding and clarifying Stefano's answer, you can use expressions to dynamically set the values for the conditions in switch, e.g.:

var i = 3
switch (i) {
    case ((i>=0 && i<=5) ? i : -1):
        console.log('0-5');
        break;

    case 6: console.log('6');
}

So in your problem, you could do something like:

var varName = "afshin"
switch (varName) {
    case (["afshin", "saeed", "larry"].indexOf(varName)+1 && varName):
      console.log("hey");
      break;

    default:
      console.log('Default case');
}

Although it is so much DRY...

Haveman answered 6/12, 2017 at 15:10 Comment(1)
not yet tested but it would be interesting to modify varName inside the case expression, expect that varName is cached thou.Hovercraft
A
8

In Node.js it appears that you are allowed to do this:

data = "10";
switch(data){
    case "1": case "2": case "3": // Put multiple cases on the same
                                  // line to save vertical space.
        console.log("small");
        break;

    case "10": case "11": case "12":
        console.log("large");
        break;

    default:
        console.log("strange");
        break;
}

This makes for much more compact code in some cases.

Atwell answered 1/9, 2015 at 9:12 Comment(3)
I think the syntax is the same as other JS environments.Aenneea
@AfshinMehrabani It might be, I have only tested it in nodejs context.Atwell
Yes. I like save vertical space!Guberniya
S
7

Here is one more easy-to-use switch case statement. which can fulfill your requirement. We can use the find method in the switch statement to get the desire output.

    switch(varname){
    case["afshin","saeed","larry"].find(name => name === varname):
        alert("Hey")
        break;
    default:
        alert('Default case');
        break;
}
Semirigid answered 11/1, 2023 at 12:38 Comment(0)
F
6

I use it like this:

switch (true){
     case /Pressure/.test(sensor): 
     {
        console.log('Its pressure!');
        break;
     }

     case /Temperature/.test(sensor): 
     {
        console.log('Its temperature!');
        break;
     }
}
Florri answered 21/2, 2018 at 12:40 Comment(4)
You don't need to use the g flag, since you're only using the regexes once and throwing them away. In fact, if you were keeping them outside the function, the g flag would harm you by trying to match from a non-0 index on subsequent .test(s. I also fixed a typo where the switch case was on sensor variable and not true constant for matching boolean expressions. See the edit.Venosity
I used this format to test against file types. Ex: case /officedocument/.test(type) && /presentation/.test(type): iconClass = "far fa-file-powerpoint red"; break;Torero
This is probably the best method of checking the input. See next comment for suggested edit.Jamey
typescriptlang.org/play?#code/…Jamey
P
5

Some interesting methods. For me the best way to solve is using .find.

You can give an indication of what the multiple cases are by using a suitable name inside your find function.

switch (varName)
{
   case ["afshin", "saeed", "larry"].find(firstName => firstName === varName):
       alert('Hey');
       break;

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

Other answers are more suitable for the given example but if you have multiple cases to me this is the best way.

Prenotion answered 25/6, 2021 at 10:30 Comment(1)
I like this approach. It also play's nicely with ESlint and other code formattersProgram
M
4

You can use the 'in' operator...
It relies on the object/hash invocation, so it's as fast as JavaScript can be.

// Assuming you have defined functions f(), g(a) and h(a,b)
// somewhere in your code,
// you can define them inside the object, but...
// the code becomes hard to read. I prefer it this way.

o = { f1:f, f2:g, f3:h };

// If you use "STATIC" code can do:
o['f3']( p1, p2 )

// If your code is someway "DYNAMIC", to prevent false invocations
// m brings the function/method to be invoked (f1, f2, f3)
// and you can rely on arguments[] to solve any parameter problems.
if ( m in o ) o[m]()
Microbicide answered 6/9, 2014 at 12:51 Comment(3)
how does this relate to switch? can you clarify it?Haveman
why would you want to make your code "hard to read". The first thing I was told as a programmer was to write code with the mindset that the next person reading your code is an axe wielding serial killer and he hates not being able to understand code.Rivalee
Hi Matt... I'm presenting it here as a proof of concept... anyway this form provides you more funcionality and flexibility... and you only use it if you want... or if you find a constrain in your usual form of doing things... consider ir as one more tool in your programmer toolbox...Microbicide
D
4

It depends. Switch evaluates once and only once. Upon a match, all subsequent case statements until 'break' fire no matter what the case says.

var onlyMen = true;
var onlyWomen = false;
var onlyAdults = false;
 
 (function(){
   switch (true){
     case onlyMen:
       console.log ('onlymen');
     case onlyWomen:
       console.log ('onlyWomen');
     case onlyAdults:
       console.log ('onlyAdults');
       break;
     default:
       console.log('default');
   }
})(); // returns onlymen onlywomen onlyadults
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
Demeanor answered 10/3, 2016 at 16:7 Comment(1)
Historically, switch is a variation of the (in)famous goto statement. The idea is that you go to one of these labels, and then continue. That is, the labels represent entry points; if you want to exit, you have to do it yourself, with either the break statement or possibly a return statement if you’re inside a function.Clishmaclaver
R
3

You can do this:

alert([
  "afshin", 
  "saeed", 
  "larry",
  "sasha",
  "boby",
  "jhon",
  "anna",
  // ...
].includes(varName)? 'Hey' : 'Default case')

or just a single line of code:

alert(["afshin", "saeed", "larry",...].includes(varName)? 'Hey' : 'Default case')

a little improvement from ErikE's answer

Rarefaction answered 6/5, 2019 at 0:33 Comment(0)
S
2

I can see there are lots of good answers here, but what happens if we need to check more than 10 cases? Here is my own approach:

 function isAccessible(varName){
     let accessDenied = ['Liam', 'Noah', 'William', 'James', 'Logan', 'Benjamin',
                        'Mason', 'Elijah', 'Oliver', 'Jacob', 'Daniel', 'Lucas'];
      switch (varName) {
         case (accessDenied.includes(varName) ? varName : null):
             return 'Access Denied!';
         default:
           return 'Access Allowed.';
       }
    }

    console.log(isAccessible('Liam'));
Stamm answered 23/9, 2018 at 15:30 Comment(1)
This is abuse of the switch statement. Just if (accessDenied.includes(varName)) return 'Access Denied!'; return 'Access Allowed.' is more than enough.Venosity
B
2

The problem with the above approaches, is that you have to repeat the several cases every time you call the function which has the switch. A more robust solution is to have a map or a dictionary.

Here is an example:

// The Map, divided by concepts
var dictionary = {
  timePeriod: {
    'month': [1, 'monthly', 'mensal', 'mês'],
    'twoMonths': [2, 'two months', '2 months', 'bimestral', 'bimestre'],
    'trimester': [3, 'trimesterly', 'quarterly', 'trimestral'],
    'semester': [4, 'semesterly', 'semestral', 'halfyearly'],
    'year': [5, 'yearly', 'annual', 'ano']
  },
  distance: {
    'km': [1, 'kms', 'kilometre', 'kilometers', 'kilometres'],
    'mile': [2, 'mi', 'miles'],
    'nordicMile': [3, 'Nordic mile', 'mil (10 km)', 'Scandinavian mile']
  },
  fuelAmount: {
    'ltr': [1, 'l', 'litre', 'Litre', 'liter', 'Liter'],
    'gal (imp)': [2, 'imp gallon', 'imperial gal', 'gal (UK)'],
    'gal (US)': [3, 'US gallon', 'US gal'],
    'kWh': [4, 'KWH']
  }
};

// This function maps every input to a certain defined value
function mapUnit (concept, value) {
  for (var key in dictionary[concept]) {
    if (key === value ||
      dictionary[concept][key].indexOf(value) !== -1) {
      return key
    }
  }
  throw Error('Uknown "'+value+'" for "'+concept+'"')
}

// You would use it simply like this
mapUnit("fuelAmount", "ltr") // => ltr
mapUnit("fuelAmount", "US gal") // => gal (US)
mapUnit("fuelAmount", 3) // => gal (US)
mapUnit("distance", "kilometre") // => km

// Now you can use the switch statement safely without the need
// to repeat the combinations every time you call the switch
var foo = 'monthly'
switch (mapUnit ('timePeriod', foo)) {
  case 'month':
    console.log('month')
    break
  case 'twoMonths':
    console.log('twoMonths')
    break
  case 'trimester':
    console.log('trimester')
    break
  case 'semester':
    console.log('semester')
    break
  case 'year':
    console.log('year')
    break
  default:
    throw Error('error')
}
Broker answered 25/2, 2019 at 14:28 Comment(0)
P
1

One of the possible solutions is:

const names = {
afshin: 'afshin',
saeed: 'saeed',
larry: 'larry'
};

switch (varName) {
   case names[varName]: {
       alert('Hey');
       break;
   }

   default: {
       alert('Default case');
       break;
   }
}
Poppas answered 11/7, 2019 at 14:54 Comment(2)
Q pls which #ecma is this?Ossy
Hi there. This is ES6Poppas
I
0

Cleaner way to handle that

if (["triangle", "circle", "rectangle"].indexOf(base.type) > -1)
{
    //Do something
}else if (["areaMap", "irregular", "oval"].indexOf(base.type) > -1)
{
    //Do another thing
}

You can do that for multiple values with the same result

Indentation answered 7/9, 2021 at 13:17 Comment(0)
D
0

If your case conditions are complex, many case value matches, or dynamic value match required, then it may be best to move that case matching logic to handler child functions.

In your case, if say you had thousands of usernames to match against for a security permissions check for example, this method is cleaner option, more extensible, exposing the high level multi-way branch logic without getting swamped in a long list of case statements.


    switch (varName)
    {     
      case checkPatternAdministrator(varName):
        alert('Hey');
        break;

      case checkPatternUserTypeA(varName):
        alert('Hey2');
        break;

      case checkPatternUserTypeB(varName):
        alert('Hey3');
        break;

      default:
        alert('Default case');
        break;
    }
 function checkPatternAdministrator(varName) {
    // Logic to check Names against list, account permissions etc.
    // return the varName if a match is found, or blank string if not
    var matchedAdministratorName = varName;

    return matchedAdministratorName;
  }
Danged answered 24/12, 2022 at 16:36 Comment(0)
C
-1

Another way of doing multiple cases in a switch statement, when inside a function:

function name(varName){
  switch (varName) {
     case 'afshin':
     case 'saeed':
     case 'larry':
       return 'Hey';
     default:
       return 'Default case';
   }
}

console.log(name('afshin')); // Hey
Costanzo answered 9/1, 2018 at 22:37 Comment(0)
B
-2

Just change the switch condition approach:

switch (true) {
    case (function(){ return true; })():
        alert('true');
        break;
    case (function(){ return false; })():
        alert('false');
        break;
    default:
        alert('default');
}
Bigamy answered 16/12, 2015 at 10:2 Comment(4)
If you put true as the switch expression, in the "case" statement(s) you can evaluate whatever you want provided you return a booleanBigamy
I think what he meant is that you can put an expression inside the function, who will evaluate and return a dynamic value for the case, thus allowing all sorts of complex conditionsHaveman
For this @StefanoFavero note you dont actually need a function, just (expression) in parenthesis, and the return value must be the input. See my answerHaveman
why you minused it?? I advocate this solution because it provides a flexibility for complex conditions. Even if you dont like funcs as conditions, you may replace them with you multiple conditions such as switch(true) { case (var1 === 0 && var2 === true): {} }Chantry
H
-2

The switch statement is used to select one of many code blocks to execute based on a condition

  1. the value in the switch expression is compared to the different values provided
  2. if there is a match the code block related to it will be executed
  3. if there is no match the default block is executed

syntax:

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

NOTE: It must be noted that if the break statement is omitted then the next block will be executed as well even if they does not match with switch expression. So don't forget to add the break statement at the end of each code block if you don't want to get the specified behaviour

A practical example: the following code returns the current day of the week in strings based on an integer (provided by 'new Date().getDay()')

switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
     day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
}

the code samples were taken from W3Schools

Hamelin answered 30/1, 2023 at 13:11 Comment(1)
this doesn't answer the specific question the user posted.Curbstone
B
-4
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Example1</title>
    <link rel="stylesheet" href="css/style.css" >
    <script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
    <script>
        function display_case(){
            var num =   document.getElementById('number').value;

                switch(num){

                    case (num = "1"):
                    document.getElementById("result").innerHTML = "You select day Sunday";
                    break;

                    case (num = "2"):
                    document.getElementById("result").innerHTML = "You select day  Monday";
                    break;

                    case (num = "3"):
                    document.getElementById("result").innerHTML = "You select day  Tuesday";
                    break;

                    case (num = "4"):
                    document.getElementById("result").innerHTML = "You select day  Wednesday";
                    break;

                    case (num = "5"):
                    document.getElementById("result").innerHTML = "You select day  Thusday";
                    break;

                    case (num = "6"):
                    document.getElementById("result").innerHTML = "You select day  Friday";
                    break;

                    case (num = "7"):
                    document.getElementById("result").innerHTML = "You select day  Saturday";
                    break;

                    default:
                    document.getElementById("result").innerHTML = "You select day  Invalid Weekday";
                    break
                }

        }
    </script>
</head>
<body>
    <center>
        <div id="error"></div>
        <center>
            <h2> Switch Case Example </h2>
            <p>Enter a Number Between 1 to 7</p>
            <input type="text" id="number" />
            <button onclick="display_case();">Check</button><br />
            <div id="result"><b></b></div>
        </center>
    </center>
</body>
Bellhop answered 5/10, 2015 at 9:7 Comment(4)
classic jquery inclusion :)Bevash
This is not how the switch statement is supposed to work. It’s just case "1":, not case (num = "1"):.Narceine
Why not put day value inside case and document.getElementById("result").innerHTML = ....outside the switch and add the day value result at the end?Prong
@Xufox I love how he literally overwrites num but it still works because the switch has already been evaluated and the assignment yields the value. This is programming by mutation/machine learning at its finest.Venosity
V
-4

You could write it like this:

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

   default: 
       alert('Default case');
       break;
}         
Viridi answered 24/2, 2016 at 11:37 Comment(1)
This is the same answer as everyone else, i will fix the " that you forgot, but think about deleting this.Detection
S
-6

For me this is the simplest way:

switch (["afshin","saeed","larry"].includes(varName) ? 1 : 2) {
   case 1:
       alert('Hey');
       break;

   default:
       alert('Default case');
       break;
}
Salpingotomy answered 21/11, 2019 at 7:29 Comment(3)
How is this the “simplest” way? Just replace this with an if statement.Narceine
If yo uhave in the array 20 elements you'd need 20 if's. This way is good for many elements.Temptation
Not at all.. Look, you already have 3 elements in your array. All you'd need is populate that array with the extra values. What Sebastian is saying here is that your switch acts exactly like an if statement so you are totally wrong, plus you did not even consider the case "2", you just assumed default is your "else".Threecolor

© 2022 - 2024 — McMap. All rights reserved.