In JavaScript, how does a switch statement compare its value against each case, and what runs after a matching case that has no break?
answer
- a case is an entry point
- control keeps running downward
- default can be fallen into
- no type conversion in the match
- one block scope for the whole body
basics
~20 sA JavaScript switch compares with strict equality and jumps to the first matching case. Without a break, execution keeps running the following clauses, default included, until a break or the end of the switch, whatever their values are.
solid answer
~50 s`switch` evaluates its expression once, then tests the `case` expressions in order using strict equality, the same comparison as `===`, so `switch ('2')` never matches `case 2`. It transfers control to the first match and evaluates no further `case` expressions. A `case` is only an entry point, not a block with an exit: without `break`, execution runs straight through the following clauses, `default` included, until it reaches a `break` or the end of the `switch`. That is the classic production bug, where a forgotten `break` makes one status run the next status's logic as well, with no error at all. If nothing matches, control goes to `default` wherever it is written, or past the `switch` if there is none. Fall-through is sometimes intended, as when stacked empty cases share one body, and a linter rule that flags unmarked fall-through catches the accidental kind.
code
javascript · 9 lineslet result;
switch ('2') {
case 2:
result = 'two';
break;
default:
result = 'other';
}
console.log(result); // othergo deeper
Recall two facts: matching uses strict equality, and a case with no break runs into the next clause. Predict the output of a short switch line by line.
Explain that case labels are jump targets inside one block scope. That accounts for fall-through into default, for later case expressions not being evaluated, and for the redeclaration error with const.
Show how the bug survives testing: a missing break throws nothing and only misbehaves for the earlier status. Ask for a lint rule on unmarked fall-through, and for tests that cover each status.
A team-wide rule is cheap here: treat fall-through as an error unless the clause is empty or carries a marker comment. The tradeoff is small noise against a silent class of logic bug.
## What a switch statement does A `switch` statement evaluates one expression, then picks a place to start running code inside its body. The body holds **`case` clauses** and at most one **`default` clause**. The steps are: 1. Evaluate the expression in the `switch (...)` head once. 2. Walk the `case` clauses in source order, evaluating each clause's expression and comparing the two values. 3. At the first match, jump to the statements after that clause. No later `case` expression is evaluated. 4. If nothing matched, jump to `default` if there is one; otherwise continue at the statement after the `switch`. From the jump onward, control simply runs downward. Most `switch` bugs come from forgetting that. ## Strict matching The comparison is **strict equality**, the same as `===`, so no type conversion happens. The consequences show up with values that look right: - `switch ('2')` does not match `case 2`. A value read from a URL or a form field arrives as a string and falls to `default`. - `switch (null)` does not match `case undefined`, because they are different types under strict equality. - `switch (NaN)` never matches `case NaN`, because `NaN` is not strictly equal to itself. - `switch (true)` matches only a case expression that evaluates to exactly `true`. A truthy value such as `'yes'` does not match. When input may arrive as a string, convert it once before the `switch` rather than writing each case twice. ## Fall-through A `case` is a **jump target**, not a block with an exit. Once execution has started, it continues through the statements of the following clauses **whether or not their values match**, and it can run into `default` too. This is **fall-through**. It ends at a `break`, at another jump such as `return`, or at the end of the `switch`. ```javascript function notify(status) { const sent = []; switch (status) { case 'paid': sent.push('receipt'); // break forgotten here case 'shipped': sent.push('tracking'); break; default: sent.push('none'); } return sent; } console.log(notify('paid')); // [ 'receipt', 'tracking' ] console.log(notify('shipped')); // [ 'tracking' ] ``` This is the production form of the bug: a paid order also sends a tracking message. Nothing throws, and a test that only exercises `shipped` passes. A case expression that fall-through passes over is not evaluated either, so its value cannot stop the run. Fall-through is sometimes what you want. **Stacked empty cases** are the accepted idiom, as `case 'mango':` directly above `case 'papaya':` makes both share one body. Non-empty fall-through is legal too, but it reads like a bug, so teams usually require a comment saying it is deliberate. ## Where default goes - `default` is conventionally last, but it may appear anywhere in the body, even first. - It only decides where execution starts when nothing matched. Clauses written below it still run by fall-through unless a `break` stops them. - Two `default` clauses in one `switch` are a `SyntaxError`. ## One scope for the whole body The `case` clauses do not create scopes of their own. All of them share **one block scope**, the `switch` body, which has two effects on `let` and `const`: - Declaring `const message` in two clauses is a `SyntaxError`, reported when the code is parsed, because the name is declared twice in one scope. - A `let` in an earlier clause is visible in a later clause, but it was never initialised if the jump landed on the later clause. Reading it there throws a `ReferenceError`. The fix for both is to wrap the clause in braces, `case 'hi': { const message = 'hi'; break; }`, so each clause gets its own block. ## Ways out of a clause | Statement | Effect inside a `switch` | |---|---| | `break` | Leaves the `switch` only, even when the `switch` sits in a loop | | `return` | Leaves the enclosing function, and so the `switch` | | `continue` | In a loop, starts the next iteration and skips code after the `switch` | | `break label` | Leaves the statement carrying that label | In a `switch` inside a loop, `break` does not end the loop. Candidates often assume it does, and the loop keeps running. Two habits keep all this cheap in practice: a lint rule that flags a non-empty clause with no `break` unless it carries a marker comment, and one test per status rather than a single test of the last branch.
- Why does declaring `const message` in two different case clauses of one JavaScript `switch` fail, and what is the fix?`case` clauses do not create scopes, so both declarations land in the single block scope of the `switch` body, and declaring one name twice in a scope is a `SyntaxError`. It fails at parse time, even if neither clause would ever run. Wrapping each clause's statements in braces gives each its own block, so both `const message` declarations become legal.
- In JavaScript, why does `switch (true) { case n && n > 5 && 'yes': ... }` fall to `default` even when `n` is 7?The case expression evaluates to the string `'yes'`, and `switch` compares with strict equality, so `true === 'yes'` is false. Truthiness plays no part in the match. The `switch (true)` pattern works only when each case expression produces an actual boolean, such as `n > 5`. Wrapping a truthy expression in `Boolean(...)` is the usual repair.
- What happens to the case expressions below the match in a JavaScript `switch`, when execution falls through them?They are not evaluated. The search for a match stops at the first success, so `case f(3):` below a matching clause never calls `f`, even though the statements after that label do run by fall-through. Case expressions above the match have already been evaluated in order, so any side effect in them has happened.
- switch compares with double equals, so the string '2' matches case 2.
- Once a case body finishes, control leaves the switch automatically.
- Fall-through re-tests the next case and runs its body only if it matches.
- default is never reached by fall-through because it only runs when nothing matches.
- Each case clause has its own block scope for let and const.
- default must be written last or the switch is a syntax error.