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.
switch (day) { case "sat": case "sun": console.log("weekend"); break; default: console.log("weekday"); }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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.
caseuses===, so"1"does not match1, andNaNnever matchesNaN. Convert the input first if needed. - Fall-through. Forgetting
breakis the classic bug. Deliberate fall-through for grouped labels (case "sat": case "sun":) is fine; comment any other use. defaultposition. Ifdefaultis not last and a case before it falls through, execution continues into the following clause. Putdefaultlast to avoid surprises.- One scope. The whole body is a single block. Two
letorconstdeclarations 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 anif...else ifchain, which reads more directly. - Lookup tables. For simply mapping values to results, an object or
Mapis shorter and has no fall-through. - Inside a loop,
breakleaves only theswitch; use a label orreturnto exit the loop, andcontinueto skip to the next iteration.
Browser support
Supported in every JavaScript engine.
Related
if...else,break,continue- Lessons: Ternary and switch, if...else