Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Statements and Declarations

The switch statement

Reference for the JavaScript switch statement: strict matching, break and fall-through, default, grouped cases, block scope and switch(true) patterns.

A switch statement evaluates an expression once and compares the result, using strict equality (===), with each case label in order. Execution begins at the first matching case and continues downward until it meets a break (or return, throw, continue). If nothing matches, it starts at default, wherever that clause is written.

JavaScript
switch (day) {
  case "sat":
  case "sun":
    console.log("weekend");
    break;
  default:
    console.log("weekday");
}

Try it

JS Matching, break and grouped cases

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Fall-through and block scope

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
switch (expression) {
  case value1:
    // statements
    break;
  case value2:
  case value3:
    // statements
    break;
  default:
    // statements
}
Part Description
expression Evaluated once; its result is compared with each case using ===.
case valueN Any expression, evaluated lazily in order until one matches.
default Optional. Used when no case matches; may appear anywhere, and only once.

Usage notes

  • Strict matching. case uses ===, so "1" does not match 1, and NaN never matches NaN. Convert the input first if needed.
  • Fall-through. Forgetting break is the classic bug. Deliberate fall-through for grouped labels (case "sat": case "sun":) is fine; comment any other use.
  • default position. If default is not last and a case before it falls through, execution continues into the following clause. Put default last to avoid surprises.
  • One scope. The whole body is a single block. Two let or const declarations with the same name in different cases collide, and a declaration in an unrun case is still in the temporal dead zone. Wrap case bodies in braces.
  • Cases can be expressions, which enables switch (true). This is often replaced by an if...else if chain, which reads more directly.
  • Lookup tables. For simply mapping values to results, an object or Map is shorter and has no fall-through.
  • Inside a loop, break leaves only the switch; use a label or return to exit the loop, and continue to skip to the next iteration.

Browser support

Supported in every JavaScript engine.