Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

How can I use a `switch` statement for several exact cases?

Quick answer

In JavaScript, switch compares its expression with each case using strict equality, so the value and type must match. Put break after each independent outcome to stop execution from continuing into later cases. Add default for values that match none of the listed cases. The example below returns a named outcome for a matching value and a fallback for an unmatched one. [S1]

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

How do I use switch when a value can be one of several exact options?

Geez

Use the value you want to check in switch (...), then add one case for each exact option. For example, suppose a small program receives a status code and should display a named outcome. Each branch below assigns a message, and break keeps that branch from continuing into the next one.

function describeStatus(status) {
  let outcome;

  switch (status) {
    case 200:
      outcome = "Success";
      break;
    case 404:
      outcome = "Not found";
      break;
    case 500:
      outcome = "Server error";
      break;
    default:
      outcome = "Unknown status";
  }

  return outcome;
}

console.log(describeStatus(404)); // "Not found"
console.log(describeStatus(201)); // "Unknown status"

A switch selects a matching case using strict equality. If none matches, execution starts at default, when present. Without a break, execution continues into later clauses, which can accidentally run more than one outcome. [S1] Here, 404 selects the second named outcome; 201 matches none of the listed numbers and uses the fallback.

Follow-up question

What does “exact” mean here? Would the string "404" match the number 404?

Geez

No. In this example, the cases are numbers, so switch ("404") does not match case 404. The comparison uses strict equality, which does not treat a numeric string and a number as the same value. [S1] If your input can arrive as text, decide what type your program expects before the switch; otherwise, a value that looks right to a person may reach default.

For instance, these calls have different results with the function above:

console.log(describeStatus(404));   // "Not found"
console.log(describeStatus("404")); // "Unknown status"

That fallback is useful for making unexpected input visible, but it does not tell you why the value was unexpected. If you need to distinguish invalid input from a recognized “unknown” state, choose and name those outcomes deliberately.

Follow-up question

Why do I need break? Could I leave it out?

Geez

Leave it out only when you intentionally want execution to continue into the next clause. Once a matching case starts, JavaScript continues through later statements until it reaches break or the end of the switch. That continuation is called fall-through, and it can reach default too. [S1]

In the example, omitting the break after case 404 would continue into the case 500 body and replace "Not found" with "Server error". For independent outcomes, put a break after each one. A deliberate exception is grouping cases that should share the same body: consecutive cases can lead to one shared action by leaving out the break between them. [S1] If you do that, make the shared behavior clear in the code so a reader can tell the fall-through is intentional.

Follow-up question

How should I adapt this for my own options and check that the fallback works?

Geez

Replace the sample numbers and outcome strings with the exact values and actions your program needs. Keep each independent case separate, add break after its action, and make default describe what should happen when no listed value matches. Then try one value you expect to match and one you expect not to match. The results shown in the first snippet—"Not found" for 404 and "Unknown status" for 201—illustrate those two paths.

Use this adaptable outline:

switch (valueToCheck) {
  case exactOptionA:
    // Set or perform outcome A
    break;
  case exactOptionB:
    // Set or perform outcome B
    break;
  default:
    // Set or perform the fallback outcome
}

The cases here are placeholders, not literal JavaScript values to copy unchanged. This guide covers exact-value matching and fall-through; it does not establish what outcomes are right for your application. Choose those based on your own requirements.

A practical checklist

  • Choose the value and type the switch should check.

  • Add one case for each exact option the program should recognize.

  • Give each independent case its intended named outcome.

  • Add break after each independent case to prevent accidental fall-through.

  • Add a default outcome for values that match no case.

  • Try one expected match and one unmatched value; check their returned outcomes.

A few more useful answers

Does `default` have to be the last clause?

It is commonly placed last so the fallback is easy to find. If execution reaches a matching case before it, break still matters: without one, execution can continue into default. [S1]

Can multiple cases share the same outcome?

Yes. Consecutive cases can share a body when you intentionally omit a break between them. Use that pattern only when those options should trigger the same action. [S1]

Does `default` mean the value is invalid?

Not necessarily. It runs when no listed case matches; your application decides whether that means invalid input, an unhandled option, or another fallback outcome. [S1]

Sources

References used for this guide.

  1. [S1] switch — JavaScript | MDN
    developer.mozilla.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work