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;
As per the above syntax, switch statement contains an expression or literal value. An expression will return a value when evaluated. The switch can includes multiple cases where each case represents a particular value.
You can use multiple conditions in the switch case same as using in JavaScript if statement. You can do that but the switch statement will switch on the result of the expression you provide. Given you have a logical and ( && ) in your expression there are two possible outcomes defined on how && works.
Case clause fall-throughsTypeScript can reports errors for fall-through cases in switch statement where the case clause is non-empty. This check is turned off by default, and can be enabled using noFallthroughCasesInSwitch .
Just put them right after each other without a break
switch (myVar) {
case 68:
case 40:
// Do stuff
break;
case 30:
// Do stuff
break;
}
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:
case 68:
case 40:
// stuff
break;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With