Handling Multiple Cases in JavaScript Switch Statements
It is possible to evaluate multiple cases within a JavaScript switch statement by leveraging the fall-through feature. This allows a matched case to continue executing until reaching a break statement or the end of the switch block.
Solution using Fall-Through:
To handle multiple cases in a JavaScript switch statement, you can use the following syntax:
switch (varName) { case "afshin": case "saeed": case "larry": alert('Hey'); break; default: alert('Default case'); }
In this example, the switch statement matches the varName against the cases "afshin", "saeed", and "larry". If any of these cases are met, the "Hey" alert message will be displayed. Otherwise, the default case will be executed, displaying the "Default case" message.
Alternative Solution for DRY Concept:
If the fall-through feature is not desired, an alternative approach to adhering to the DRY (Don't Repeat Yourself) principle is to use an object to map case values to functions:
const cases = { "afshin": () => alert('Hey, Afshin!'), "saeed": () => alert('Hey, Saeed!'), "larry": () => alert('Hey, Larry!') }; const handleCase = (varName) => { if (cases[varName]) { cases[varName](); } else { alert('Default case'); } };
In this example, the handleCase function takes a case value as input. If the value exists in the cases object, the corresponding function is invoked. If the case value is not found, the default case alert message is displayed.
The above is the detailed content of **How to Evaluate Multiple Cases in JavaScript Switch Statements**. For more information, please follow other related articles on the PHP Chinese website!