Home >Web Front-end >JS Tutorial >Can You Use Multiple Cases in a JavaScript Switch Statement?
Multiple Cases in a JavaScript Switch Statement
In JavaScript, it's not possible to specify multiple cases in a single case statement of a switch construct as shown in the initial code example. To handle such scenarios where multiple cases require the same code execution, the "fall-through" feature of the switch statement can be used.
Consider the revised code:
switch (varName) { case "afshin": case "saeed": case "larry": alert('Hey'); break; default: alert('Default case'); }
With the fall-through feature, when a case matches, the code execution continues to the next case until a break (or the end of the switch statement) is encountered. This way, the code for handling "afshin," "saeed," and "larry" can be grouped into a single case statement, adhering to the DRY (Don't Repeat Yourself) principle.
Therefore, using the fall-through feature of the switch statement provides a viable solution for handling multiple cases in JavaScript, promoting code efficiency and maintainability.
The above is the detailed content of Can You Use Multiple Cases in a JavaScript Switch Statement?. For more information, please follow other related articles on the PHP Chinese website!