JavaScript switch, case, default and Fallthrough
Quick answer
A switch statement compares one evaluated input with case expressions and begins executing at a matching case. It is useful for discrete values such as menu commands.
How it works
Cases match using strict equality. break exits the switch; without it execution continues into subsequent case bodies even if their labels do not match. default handles no match (and can also be reached by fallthrough). Adjacent labels can intentionally share one body. Lexical declarations in cases share the switch block unless explicitly wrapped in separate blocks.
const command = "save";switch (command) { case "save": console.log("saved"); break; case "open": console.log("opened"); break; default: console.log("unknown"); }Expected output in Node.js:
savedThe matching case runs and break exits.
const day = 6;switch (day) { case 6: case 7: console.log("weekend"); break; default: console.log("weekday"); }Expected output in Node.js:
weekendTwo adjacent labels deliberately share a body.
Common mistakes
A numeric case 1 does not match string "1". Missing break is not automatically wrong, but document intentional fallthrough.
Practice
Map a known command to a message and return an explicit default for other commands.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript switch, case, default and Fallthrough — Knowledge Check
Apply the taught concept and reason about the result.
Which case matches switch("1")?
What does an unlabeled break inside a switch do?
What is fallthrough?
When is default selected during matching?
Why put lexical declarations in braces inside separate cases?