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]
The question, the details, the next step.
A practical checklist
Choose the value and type the
switchshould check.Add one
casefor each exact option the program should recognize.Give each independent case its intended named outcome.
Add
breakafter each independent case to prevent accidental fall-through.Add a
defaultoutcome 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.
- [S1] switch — JavaScript | MDN developer.mozilla.org · Checked
