JavaScript Tip: Checking Multiple Cases in a Switch Statement
I recently worked on a JavaScript function that used a switch
statement to branch the logic based on a certain value, but each action applied to multiple different cases. It would be overkill to repeat the same logic in multiple case
statements. Fortunately, JavaScript can handle this, although the structure of the code might not be what you’d expect.
My instinct is to try something like this:
switch (myVariable) { case "A", "B", "C": // Do something break; case "D", "E": // Do something else break; default: // Default case break; }
But that doesn’t work.
The correct syntax makes use of the ‘fall-through’ behavior of the JavaScript switch statement. Once it matches a case, it will keep executing code until it either hits a break
statement or the end of the switch
.
This code will do the trick:
switch (myVariable) { case "A": case "B": case "C": // Do something break; case "D": case "E": // Do something else break; default: // Default case break; }
In this example, if the value of myVariable is A, B, or C, it will execute the code under case "C":
.
I had run into the same thing before, though I attempted to use an or on my values. Thankfully, Mozilla Developer Network set me straight. Your solution is in perfect keeping with their example.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch#Examples