How to use multiple cases in a switch statement - javascript

I found this answer in a question similar to mine, but I still have a doubt.
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');
}
This means "if varName is afshin && saeed && larry", or it means "if varName is afshin || saeed || larry"?
Thanks in advance!

As the previous answer said
A matched case will run until a break (or the end of the switch statement) is found
To better understand how this works, consider this example:
switch (varName) {
case "afshin":
alert("afshin");
case "saeed":
alert("saeed");
case "larry":
alert('larry');
break;
default:
alert('Default case');
}
Since only the "larry" case has the break,
if varName == "afshin", you will get 3 alerts ("afshin","saeed","larry")
if varName == "saeed", you will get 2 alerts ("saeed","larry")
if varName == "larry", you will get 1 alert ("larry")
This is why it is very important to break all of your cases unless you absolutely mean for the case statement to drop through to the next one.
Long story short, writing:
case "afshin":
case "saeed":
case "larry":
alert("hi");
break;
is the equivalent of
if(varName == "afshin" || varName == "saeed" || varName == "larry"){
alert("hi");
}

Related

What is empty switch case in javascript [duplicate]

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.
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');
}
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);
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();
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
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');
}
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.
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');
}
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...
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.
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;
}
}
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.
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>
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]()
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
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'));
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')
}
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;
}
}
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;
}
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;
}
The switch statement is used to select one of many code blocks to execute based on a condition
the value in the switch expression is compared to the different values provided
if there is a match the code block related to it will be executed
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
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
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
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');
}
<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>
You could write it like this:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
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;
}

Switch case match with string

function getFieldType(value){
var type = "";
switch(value){
case "TEXT_BOX":
type=FieldTypeEnum.TEXT_BOX;
break;
case "PASSWORD":
type=FieldTypeEnum.PASSWORD;
break;
case "CHECK_BOX":
type=FieldTypeEnum.CHECK_BOX;
break;
case "RADIO_BUTTON":
type=FieldTypeEnum.RADIO_BUTTON;
break;
case "DROP_DOWN":
type=FieldTypeEnum.DROP_DOWN;
break;
case "SEARCH_CARD_BOX":
type=FieldTypeEnum.SEARCH_CARD_BOX;
break;
case "STATE_DROP_DOWN":
type=FieldTypeEnum.STATE_DROP_DOWN;
break;
case "ID_DROP_DOWN":
type=FieldTypeEnum.ID_DROP_DOWN;
break;
case "GENDER_DROP_DOWN":
type = FieldTypeEnum.GENDER_DROP_DOWN;
break;
default:
type = "";
}
return type;
}
I want to combined three drop down box (STATE_DROP_DOWN, ID_DROP_DOWN, GENDER_DROP_DOWN)into one .
Means I want something like below :
case String.endwith("_DROP_DOWN"):
type=FieldTypeEnum.ID_DROP_DOWN;
break;
Is it possible in JavaScript? If yes then how?
It is possible, in a javascript switch/case statement you can compare for string equality (which evaluates to true or false) or more complex statements which just as when testing for string equality, also evaluate to true or false (e.g. String.endwith("_DROP_DOWN")). However personally I would prefer the following:
STATE_DROP_DOWN:
// intentional fall through
ID_DROP_DOWN:
// intentional fall through
GENDER_DROP_DOWN:
//.. do your stuff
break;
I believe this way it is more clearly through which switch case you are falling in a certain situation.
You can put a ternary operator in the case, and test if it ends with "DROP_DOWN" return value otherwise blank string.
switch(value){
case value.endsWith("_DROP_DOWN") ? value : '' {
type=FieldTypeEnum.ID_DROP_DOWN;
break;
}
}

JavaScript: right switch-case statement

My code is such:
switch(typeof src) {
case 'string':
case 'boolean':
return String(src).toLowerCase().indexOf(value.toLowerCase()) > -1;
case 'object':
return true;
default:
return false;
}
but code checker say that: n unconditional "break" statement shall terminate every non-empty switch-clause
will it be right and normal if I will write it so?
switch(typeof src) {
case 'string':
case 'boolean':
return String(src).toLowerCase().indexOf(value.toLowerCase()) > -1;
break;
case 'object':
return true;
break;
default:
return false;
// in default i need it or not?
}
or I missed somewhat else?
Your code checker is wrong then, because a return terminates the entire function in which the switch statement resides.
Anything after a return (like the break it wants you to put there) will be unreachable and never executed.
Whether or not this is beautiful or good practise is debatable, but I would say it is OK.
If you do not have a return statement or anything else that terminates the current block or jumps out of it (like continue inside a loop), then you usually want to put a break and the end of each case block to prevent fallthrough, but there are actually cases where you want fallthrough.
So your code checker is more of an opinion checker really.
No, break statement is not necessary if you return from a default case.
You must add break statement for all your cases which you want to operate and stop switch's work, otherwise default is operated returning from function.
Switch Pattern from "JavaScript Patterns" by Stoyan Stefanov.
var inspect_me = 0,
result = '';
switch (inspect_me) {
case 0:
result = "zero";
break;
case 1:
result = "one";
break;
default:
result = "unknown";
}

Switch case - else condition

<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d = new Date();
var theDay = d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>
If the theDay = 5, then we display Finally Friday. I want if theDay !=5, then display 'Finally Something'.. similarly for others too...
Is it possible without an If/else condition. If the case 5 does not execute, can i do something else in that place?
Is it possible without an If/else condition. If the case 5 does not execute, can i do something else in that place?
No.
The switch statement will execute the first matching case, and then keep going (ignoring all further case labels) until it gets to either a break statement or the end of the switch block - but even though you can "fall through" to subsequent cases by omitting the break statement the switch does not provide any mechanism to say "do something when this case isn't matched/executed, but also keep trying to look for a matching case".
What you are describing would normally be done with a series of if/else statements:
var d = new Date(),
theDay=d.getDay(),
matched = false;
if (theDay === 5) {
matched = true;
document.write("Finally Friday");
} else {
// your != 5 case here
}
if (theDay === 6) {
matched = true;
document.write("Super Saturday");
} else {
// your != 6 case here
}
if (theDay === 0) {
matched = true;
document.write("Sleepy Sunday");
} else {
// your != 0 case here
}
// default when none matched:
if (!matched) {
document.write("I'm looking forward to this weekend!");
}
Note that I've added a matched flag to allow the default to work. And note that there are no else if statements because you need every if/else pair to execute.
If you are really determined to use a switch statement you could do something silly like the following:
var d = new Date(),
theDay = d.getDay(),
c,
cases = { // pre-list all the "not" cases
"!5" : true,
"!6" : true,
"!0" : true
};
// add case for theDay and remove the "not" case for theDay (if there is one)
cases[theDay] = true;
if (cases["!" + theDay])
delete cases["!" + theDay];
for (c in cases) {
switch(c) {
case "5":
document.write("Finally Friday");
break;
case "!5":
document.write("Finally Something");
break;
case "6":
document.write("Super Saturday");
break;
case "!6":
document.write("Finally Something - but not 6");
break;
case "0":
document.write("Sleepy Sunday");
break;
case "!0":
document.write("Finally Something - but not 0");
break;
default:
document.write("I'm looking forward to this weekend!");
}
}
If you need the cases to execute in a specific order use an array rather than an object.
Its like switch does a jump to the matching case, if it doesn't match it will jump to what matches. The answer to your question "If the case 5 does not execute, can i do something else in that place?" is No, because it never reaches that case at all. It jumps to the next matching case or default.
Is it possible without an If/else condition. If the case 5 does not execute, can i do something else in that place?
Use a default code block as seen below. Anything that doesn't match the cases will fallback to the default one.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
How this works:
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
If there is no match, the default code block is executed.
A standard if/else would be the best way to achieve this. I wonder why you want to do it without.
That said, It's not very elegant, but you could try adding the following to the top of your switch statement:
case 0:
case 1:
case 2:
case 3:
case 4:
case 6:
document.write("Finally Something");
Giving you:
switch (theDay)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 6:
document.write("Finally Something");
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
You can do something like:
var something = 0;
switch (theDay) {
case 5:
document.write("Finally Friday");
something = 15;
break;
case 6:
document.write("Super Saturday");
something = 16;
break;
case 0:
document.write("Sleepy Sunday");
something = 20;
break;
default:
document.write("I'm looking forward to this weekend!");
}
switch (something) {
case 15: document.write("Not Friday"); break;
case 16: document.write("Not Saturday"); break;
case 20: document.write("Not Sunday"); break;
default: document.write("Nothing"); break;
}
Overly complicated answers.
Simplify.
var switchElse = true;
switch (CHECK_SOMETHING)
{
case "SOME_VALUE":
...DO SOMETHING...
switchElse = false;
break;
default:
}
if (switchElse)
{
...DO ELSE...
}
The only solution that can be formulated without a compare.
USE "DEFAULT" PATTERN
var myValue = "Friday"
switch (CHECK_SOMETHING)
{
case "SOME_VALUE":
myValue = "Some Other Day";
default:
}

Why does this switch statement fail?

switch (t.value) {
case < 5:
alert('hi');
break;
}
I know it's the part where I have "< 5". How do I make it so that it has a case where t.value is less than 5??
switch only supports equality comparisons.
if (t.value < 5) {
alert('hi');
}
I don't know if it fits your particular case, but you could also do something like this:
switch (t.value) {
case 5:
case 4:
case 3:
case 2:
case 1:
alert('hi');
break;
}
An if statement seems best suited for this purpose, but although I do not recommend it the fact that JavaScript will let you switch on any datatype (and not just numbers/enums like some languages) means you can do this:
switch(true) {
case t.value < 5:
// do something
break;
case t.value >= 112:
// do something
break;
case someOtherVar == 17:
// do something
break;
case x == 7:
case y == "something":
case z == -12:
case a == b * c:
// works with fallthrough
break;
case someFunc():
// even works on a function call (someFunc() should return true/false)
break;
default:
// whatever
break;
}
The above should select whichever case matches first, noting that several if not all of the cases could be true.
In a way that style is more readable than a long series of if/else if, but I wouldn't use it in a team development environment where it could confuse other developers.
Another, more conventional use of switch for your less than 5 scenario would be as follows (assuming you know the range that t.value could possibly be):
switch(t.value) {
case 0:
case 1:
case 2:
case 3:
case 4:
// do something
break;
case 5:
// etc
}
switch statements don't support less-than or greater-than comparisons (or anything other than equals). Use:
if (t.value < 5) {
alert("hi");
}
default:
if(t.value< 5)
alert('hi');
break;
Maybe it's you want!

Categories

Resources