JavaScript, Typescript switch statement: way to run same code for two cases?
JavascriptTypescriptSwitch StatementJavascript Problem Overview
Is there a way to assign two different case values to the same block of code without copy and pasting? For example, below 68 and 40 should execute the same code, while 30 is not related.
case 68:
//Do something
break;
case 40:
//Do the same thing
break;
case 30:
//Do something different
break;
Is it incorrect to think something like this should work (even though it obviously doesn't)?
case 68 || 40:
//Do something
break;
case 30:
//Do something else
break;
Javascript Solutions
Solution 1 - Javascript
Just put them right after each other without a break
switch (myVar) {
case 68:
case 40:
// Do stuff
break;
case 30:
// Do stuff
break;
}
Solution 2 - Javascript
Yes, you just put the related case
statements next to each other, like this:
case 40: // Fallthrough
case 68:
// Do something
break;
case 30:
// Do something different
break;
The Fallthrough
comment is there for two reasons:
- It reassures human readers that you're doing this deliberately
- It silences warnings from Lint-like tools that issue warnings about possible accidental fallthrough.
Solution 3 - Javascript
case 68:
case 40:
// stuff
break;
Solution 4 - Javascript
Cleaner way to do that
if ([68, 48, 22, 53].indexOf(value) > -1)
//Do something
else if ([44, 1, 0, 24, 22].indexOf(value) > -1)
//Do another
You can do that for multiple values with the same result
Solution 5 - Javascript
Switch cases can be clubbed as shown in the dig.
Also, It is not limited to just two cases, you can extend it to any no. of cases.
Solution 6 - Javascript
You should use:
switch condition {
case 1,2,3:
// do something
case 4,5:
// do something
default:
// do something
}
Cases should be comma-separated.