Fundamentalsbeginner
Switch Statements and Fall-Through
How switch statements compare values with strict equality and why forgetting break causes cases to 'fall through.'
The switch statement offers a cleaner alternative to long if/else if chains when comparing one value against several possible matches, but its fall-through behavior is a frequent source of bugs for anyone new to it, which makes it a reliable interview topic for testing attention to control-flow detail.
A switch statement without breaks is like walking into a building through the right door but then finding all the internal doors between rooms wedged open — you keep walking through every room after that, whether you meant to or not, until you hit an actual closed door (break).
Key Concepts
1
A switch evaluates its expression once and compares the result against each case value using strict equality (===), not loose equality — so switch(x) { case '1': ... } will not match if x is the number 1. When a matching case is found, execution begins there and continues executing every subsequent line, including the code under following case labels, until it hits a break, return, throw, or the end of the switch block. This 'fall-through' behavior is by design, not a bug, and it can actually be used intentionally to group multiple case labels that should run the same code.
switchcase===switch(x) { case '1': ... }x
2
A default case, if present, runs when no other case matches; it doesn't have to be the last label physically, but it is conventionally placed last for readability, and it should still typically end with a break if it isn't already the final statement, to avoid accidentally falling into nothing (which is harmless) or being placed awkwardly mid-switch (which is confusing).
defaultbreak
3
Many style guides and linters (like ESLint's no-fallthrough rule) flag missing break statements precisely because forgetting one is such a common accidental bug, while explicitly documenting an intentional fall-through with a comment like // falls through is considered acceptable practice.
no-fallthroughbreak// falls through