A switch statement compares one value against several case labels and runs the code of the first label that matches. It is a tidy alternative to a long chain of else if tests when you compare the same expression with fixed values. This is the standard "javascript switch case" pattern, and you need break to stop it from running into the next case.
The comparison uses strict equality (===), so no type conversion happens. The value "1" does not match case 1.
You write switch (expression), then a set of case value: labels, and optionally a default: label that runs when nothing else matches.
JavaScript evaluates day once, finds the first case whose value is strictly equal to it, and starts running from there. The break statement leaves the switch. The last branch does not need break because nothing follows it.
Without break, execution continues into the next case, whether or not that case matches. This is called fall-through.
Forgetting break is the most common switch bug. Fall-through is sometimes intentional, so add a comment such as // falls through when you mean it. ESLint's no-fallthrough rule warns about accidental cases.
Stacking empty case labels is the clean way to give several values the same behaviour.
Here return ends the function, so no break is needed.
default runs when no case matches. It is optional and may appear anywhere in the switch, though putting it last is conventional and easier to read. Use it to handle unexpected input, for example by returning an error value or throwing.
Because switch uses ===, mixing types fails silently:
Convert the value first, for example with Number(input).
Also remember that the whole switch body is a single block scope. Declaring let or const in two cases with the same name is an error. Wrap the case body in its own braces:
A case can be any expression, not only a literal. The switch (true) idiom lets you test ranges, but it reads much like an if chain.
For ranges, a plain if / else if chain is usually clearer.
| Situation | Best choice |
|---|---|
| One value, many fixed options | switch |
| Ranges or mixed conditions | if / else if |
| Mapping a key to a value | Object or Map lookup |
| Choosing between two values | Ternary operator |
For a pure mapping, an object is shorter and has no fall-through risk:
It uses strict equality (===). A string "5" never matches case 5.
No, it is optional. It is good practice to include it so unexpected values are handled.
Yes. Any value that works with === can be used, including strings, numbers and booleans.
Differences are negligible in real programs because engines optimise both. Choose by readability.
switch compares one expression with case values using ===.break (or return) to avoid fall-through.default for unmatched values.if / else if for ranges and an object lookup for simple mappings.