skip to content

Statement and Parsing Hazards

Semicolon insertion breaking a return, a switch that falls through, and parseInt without a radix are small bugs with long debugging sessions. Interviewers use them to test careful reading.

part ofJavaScriptread it →
on this pageshow

questions

6

In JavaScript, how does a switch statement compare its value against each case, and what runs after a matching case that has no break?

level: juniorimportance: must knowfreq 50%

answer

  1. a case is an entry point
  2. control keeps running downward
  3. default can be fallen into
  4. no type conversion in the match
  5. one block scope for the whole body

basics

~20 s

A 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 lines
javascript
let result;
switch ('2') {
  case 2:
    result = 'two';
    break;
  default:
    result = 'other';
}
console.log(result); // other

go deeper

for a junior

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.

for a middle

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.

for a senior

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.

for a principal

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.
open as a page

In JavaScript, why does a function return undefined when the object literal after return starts on the next line, and how do you fix it?

level: middleimportance: must knowfreq 55%

basics

~20 s

Automatic semicolon insertion ends the statement: the grammar forbids a line break between return and its expression, so the parser reads a bare return and the next line never runs. Start the expression on the return line.

open as a page

In JavaScript, what is the difference between encodeURI and encodeURIComponent, and which do you use for a value placed inside a query string?

level: juniorimportance: should knowfreq 42%

basics

~20 s

encodeURI is for an already assembled URL and leaves URL syntax such as / ? & = # alone. encodeURIComponent also escapes those characters, so it is the one for a single dynamic value such as a query parameter.

open as a page

In JavaScript, why does parseInt read the page parameters `2abc` as 2 and `1e3` as 1, and how does Number differ?

level: middleimportance: should knowfreq 47%

basics

~20 s

parseInt reads digits from the start and silently stops at the first invalid character, so 2abc gives 2 and 1e3 gives 1. Number converts the whole string or returns NaN, giving NaN and 1000 here.

open as a page

A JavaScript file written without semicolons starts throwing `TypeError: x is not a function` right after someone adds a line beginning with `(`; why does that happen, and how do you stop it recurring?

level: seniorimportance: should knowfreq 33%

basics

~20 s

No semicolon is inserted, because a line starting with ( can legally continue the previous expression as a call. Insertion needs an offending token or a restricted production. Prefix such lines with a semicolon, and enforce it with a linter.

open as a page

In JavaScript, how do a labelled break and a labelled continue behave inside nested loops, and what can a label not do?

level: middleimportance: nice to knowfreq 27%

basics

~20 s

A labelled break ends the named statement and continues after it; a labelled continue starts the named loop's next iteration. A label is no goto: the jump must sit inside the labelled statement, in the same function.

open as a page