switch
In JavaScript, the switch keyword starts a statement that compares one value against a list of case clauses and runs the code from the first clause that matches. An optional default clause runs when no case matches. Matching uses strict equality (===), so "1" doesn’t match 1 and NaN never matches anything.
Once a clause matches, execution runs to the end of the switch body unless a break, return, or throw leaves it first. Running on into the next clause is called fall-through.
The whole body is one block scope, so two clauses can’t both declare the same let or const name, and a using declaration directly inside a clause is a SyntaxError. Braces around a clause’s statements give them their own scope. For two or three branches, if and else are the common alternative.
JavaScript switch Keyword Syntax
A switch statement has the following form:
switch (<expression>) {
case <value1>:
[<statements>]
[case <value2>:
[<statements>]]
[default:
[<statements>]]
}
The body allows at most one default clause, in any position.
JavaScript switch Keyword Examples
A switch statement maps HTTP status codes to messages, with one case that falls through:
> function describeStatus(code) {
… switch (code) {
… case 200:
… return "OK";
… case 301:
… case 302:
… return "Redirect";
… case 404:
… return "Not Found";
… default:
… return "Unknown";
… }
… }
undefined
> describeStatus(302)
'Redirect'
> describeStatus("404")
'Unknown'
The empty case 301: clause falls through to case 302:, so both codes share a result. The string "404" isn’t strictly equal to 404, so it reaches default.
Without a break, a matching clause keeps running into the clauses below it:
> switch ("small") {
… case "small":
… console.log("Fits a small box");
… case "medium":
… console.log("Fits a medium box");
… break;
… case "large":
… console.log("Fits a large box");
… }
Fits a small box
Fits a medium box
undefined
The break in the "medium" clause stops execution before "large".
JavaScript switch Keyword Use Cases
- Choosing a branch from one value with several known options
- Mapping status codes, commands, or action types to results
- Grouping values that share a branch by stacking empty
caseclauses - Handling each kind of message in a reducer or event handler
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 4, 2026