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.
The JavaScript switch case is a multiple if else statement. It takes a conditional expression just like an if statement but can have many conditions—or cases—that can match the result of the expression to run different blocks of code.
You can only include one default case in a switch statement, or JavaScript will throw an error. Finally, you need to include the break keyword in each case clause's body to stop the switch statement's execution once a matching case is found.
In addition to if...else , JavaScript has a feature known as a switch statement. switch is a type of conditional statement that will evaluate an expression against multiple possible cases and execute one or more blocks of code based on matching cases.
Microsoft C doesn't limit the number of case values in a switch statement. The number is limited only by the available memory. ANSI C requires at least 257 case labels be allowed in a switch statement.
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'); }
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