Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement for multiple cases in JavaScript

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.

like image 869
Afshin Mehrabani Avatar asked Nov 03 '12 09:11

Afshin Mehrabani


People also ask

Can switch case have multiple conditions in JavaScript?

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.

How many cases can a switch statement have in JavaScript?

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.

Can you do a switch case in JavaScript?

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.

How many cases a switch statement have?

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.


1 Answers

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'); } 
like image 133
kennytm Avatar answered Sep 18 '22 16:09

kennytm