How do you match multiple cases to the same block in a JavaScript switch statement? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you match multiple cases to the same block in a JavaScript switch statement?

message-square
0

To match multiple cases to the same block in a JavaScript switch statement, stack consecutive case labels without a break statement between them so execution falls through into the shared body (case "a": case "b": ... break;). JavaScript compares the switch expression against each case value using strict equality (===), so grouping cases works cleanly for exact literals while falling through to a single shared block avoids duplicating logic.


1. Stacking case Labels for Fall-Through Execution

Place multiple case clauses directly above one another with a single shared statement block and break at the end so any matching label executes that block and exits the switch:

// Group multiple matching values into a single switch block via fall-through
function getHttpCategory(statusCode) {
  if (typeof statusCode !== "number") {
    throw new TypeError("Expected statusCode to be a number.");
  }

  switch (statusCode) {
    case 200:
    case 201:
    case 204:
      return "success";

    case 400:
    case 401:
    case 403:
    case 404:
      return "client-error";

    case 500:
    case 502:
    case 503:
      return "server-error";

    default:
      return "other";
  }
}

// Example usage:
console.log(getHttpCategory(201)); // "success"
console.log(getHttpCategory(404)); // "client-error"
console.log(getHttpCategory(503)); // "server-error"
  • Intentional fall-through: Stacking empty case labels before a block is the standard, readable way to share a branch across multiple values.
  • Always terminate with break or return: Without a break or return, execution continues into the next case block below it.

2. Grouping String Variants and Avoiding Accidental Fall-Through

When normalizing user input or command aliases, group multiple string cases together and keep every branch self-contained so adding a new label stays straightforward:

// Match multiple command aliases to the same action handler
function handleCommand(command) {
  const normalized = String(command).trim().toLowerCase();

  switch (normalized) {
    case "q":
    case "quit":
    case "exit":
      return { action: "close", exitCode: 0 };

    case "h":
    case "help":
    case "?":
      return { action: "show-help", exitCode: 0 };

    default:
      return { action: "unknown", exitCode: 1 };
  }
}

// Example usage:
console.log(handleCommand("  Exit ")); // { action: "close", exitCode: 0 }
console.log(handleCommand("?"));       // { action: "show-help", exitCode: 0 }
  • Normalize inputs beforehand: Trimming and lowercasing once before switch keeps case labels clean and predictable.
  • Include a default branch: Handles unexpected values explicitly instead of silently ignoring them.

3. Strict Equality (===) Limits and When to Use switch (true) or Set

Because switch uses strict equality (===), it cannot directly match ranges or predicates in case expressions—use switch (true) when evaluating boolean conditions, or a Set / lookup map when matching dynamic collections of values:

// Use switch(true) for boolean conditions or a Set for dynamic multi-match checks
function describeScoreBand(score) {
  if (typeof score !== "number" || Number.isNaN(score)) {
    throw new TypeError("Expected score to be a valid number.");
  }

  switch (true) {
    case score >= 90:
      return "A";
    case score >= 75:
      return "B";
    case score >= 50:
      return "C";
    default:
      return "Needs practice";
  }
}

// Example usage:
console.log(describeScoreBand(82)); // "B"
const retryableCodes = new Set([408, 429, 502, 503, 504]);
console.log(retryableCodes.has(503)); // true
  • Switch checks ===: switch (x) evaluates x === caseExpr, which does not work for ranges like score >= 90.
  • Use Set.has() for dynamic lists: When allowed values come from runtime config or a large set, retryableCodes.has(code) is cleaner than dozens of case lines.