Home > Web Front-end > JS Tutorial > body text

**How to Evaluate Multiple Cases in JavaScript Switch Statements**

Mary-Kate Olsen
Release: 2024-10-24 04:27:02
Original
612 people have browsed it

**How to Evaluate Multiple Cases in JavaScript Switch Statements**

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');
}
Copy after login

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');
    }
};
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!