Home >Web Front-end >JS Tutorial >**How to Evaluate Multiple Cases in JavaScript Switch Statements**

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 04:27:02674browse

**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');
}

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!

Statement:
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
Previous article:Build small toolsNext article:Build small tools