Switch Statement Should Have a Default Case
ID |
javascript.default_case |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
JavaScript |
Tags |
best-practice, control-flow |
Description
A switch statement without a default clause silently does nothing when the input does not match any of the listed case values:
// Bad — what happens for any other status?
switch (status) {
case "open": handleOpen(); break;
case "closed": handleClosed(); break;
}
Rationale
Missing defaults are one of the most common sources of "the bug only happens in production" — a new enum value, a renamed status, an unexpected user input quietly falls through every branch. Adding a default forces the developer to make a deliberate decision about the unmatched case at the moment the switch is written.
Remediation
Add a default clause. If the unmatched case is genuinely impossible, throw or assert:
switch (status) {
case "open": handleOpen(); break;
case "closed": handleClosed(); break;
default:
throw new Error("Unknown status: " + status);
}
If the unmatched case truly should be a silent no-op, an empty default clause documents that intent:
switch (status) {
case "open": handleOpen(); break;
case "closed": handleClosed(); break;
default: // intentionally ignored
}
Notes
The rule fires only when no default clause is present at all. A default: clause with an empty body is accepted because it shows the unmatched case was considered.