switch
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Theswitch
statement evaluates anexpression, matching the expression's value against a series ofcase
clauses, and executesstatements after the firstcase
clause with a matching value, until abreak
statement is encountered. Thedefault
clause of aswitch
statement will be jumped to if nocase
matches the expression's value.
Try it
const expr = "Papayas";switch (expr) { case "Oranges": console.log("Oranges are $0.59 a pound."); break; case "Mangoes": case "Papayas": console.log("Mangoes and papayas are $2.79 a pound."); // Expected output: "Mangoes and papayas are $2.79 a pound." break; default: console.log(`Sorry, we are out of ${expr}.`);}
Syntax
switch (expression) { case caseExpression1: statements case caseExpression2: statements // … case caseExpressionN: statements default: statements}
expression
An expression whose result is matched against each
case
clause.caseExpressionN
OptionalA
case
clause used to match againstexpression
. If the value ofexpression
matches the value of anycaseExpressionN
, execution starts from the first statement after thatcase
clause until either the end of theswitch
statement or the first encounteredbreak
.default
OptionalA
default
clause; if provided, this clause is executed if the value ofexpression
doesn't match any of thecase
clauses. Aswitch
statement can only have onedefault
clause.
Description
Aswitch
statement first evaluates its expression. It then looks for the firstcase
clause whose expression evaluates to the same value as the result of the input expression (using thestrict equality comparison) and transfers control to that clause, executing all statements following that clause.
The clause expressions are only evaluated when necessary — if a match is already found, subsequentcase
clause expressions will not be evaluated, even when they will be visited byfall-through.
switch (undefined) { case console.log(1): case console.log(2):}// Only logs 1
If no matchingcase
clause is found, the program looks for the optionaldefault
clause, and if found, transfers control to that clause, executing statements following that clause. If nodefault
clause is found, the program continues execution at the statement following the end ofswitch
. By convention, thedefault
clause is the last clause, but it does not need to be so. Aswitch
statement may only have onedefault
clause; multipledefault
clauses will result in aSyntaxError
.
Breaking and fall-through
You can use thebreak
statement within aswitch
statement's body to break out early, often when all statements between twocase
clauses have been executed. Execution will continue at the first statement followingswitch
.
Ifbreak
is omitted, execution will proceed to the nextcase
clause, even to thedefault
clause, regardless of whether the value of that clause's expression matches. This behavior is called "fall-through".
const foo = 0;switch (foo) { case -1: console.log("negative 1"); break; case 0: // Value of foo matches this criteria; execution starts from here console.log(0); // Forgotten break! Execution falls through case 1: // no break statement in 'case 0:' so this case will run as well console.log(1); break; // Break encountered; will not continue into 'case 2:' case 2: console.log(2); break; default: console.log("default");}// Logs 0 and 1
In the appropriate context, other control-flow statements also have the effect of breaking out of theswitch
statement. For example, if theswitch
statement is contained in a function, then areturn
statement terminates the execution of the function body and therefore theswitch
statement. If theswitch
statement is contained in a loop, then acontinue
statement stops theswitch
statement and jumps to the next iteration of the loop.
Lexical scoping
Thecase
anddefault
clauses are likelabels: they indicate possible places that control flow may jump to. However, they don't create lexicalscopes themselves (neither do they automatically break out — as demonstrated above). For example:
const action = "say_hello";switch (action) { case "say_hello": const message = "hello"; console.log(message); break; case "say_hi": const message = "hi"; console.log(message); break; default: console.log("Empty action received.");}
This example will output the error "Uncaught SyntaxError: Identifier 'message' has already been declared", because the firstconst message = 'hello';
conflicts with the secondconst message = 'hi';
declaration, even when they're within their own separate case clauses. Ultimately, this is due to bothconst
declarations being within the same block scope created by theswitch
body.
To fix this, whenever you need to uselet
orconst
declarations in acase
clause, wrap it in a block.
const action = "say_hello";switch (action) { case "say_hello": { const message = "hello"; console.log(message); break; } case "say_hi": { const message = "hi"; console.log(message); break; } default: { console.log("Empty action received."); }}
This code will now outputhello
in the console as it should, without any errors.
Examples
Using switch
In the following example, ifexpr
evaluates toBananas
, the program matches the value with casecase 'Bananas'
and executes the associated statement. Whenbreak
is encountered, the program breaks out ofswitch
and executes the statement followingswitch
. Ifbreak
were omitted, the statement for thecase 'Cherries'
would also be executed.
switch (expr) { case "Oranges": console.log("Oranges are $0.59 a pound."); break; case "Apples": console.log("Apples are $0.32 a pound."); break; case "Bananas": console.log("Bananas are $0.48 a pound."); break; case "Cherries": console.log("Cherries are $3.00 a pound."); break; case "Mangoes": case "Papayas": console.log("Mangoes and papayas are $2.79 a pound."); break; default: console.log(`Sorry, we are out of ${expr}.`);}console.log("Is there anything else you'd like?");
Putting the default clause between two case clauses
If no match is found, execution will start from thedefault
clause, and execute all statements after that.
const foo = 5;switch (foo) { case 2: console.log(2); break; // it encounters this break so will not continue into 'default:' default: console.log("default"); // fall-through case 1: console.log("1");}
It also works when you putdefault
before all othercase
clauses.
Taking advantage of fall-through
This method takes advantage of the fact that if there is nobreak
below acase
clause, execution will continue to the nextcase
clause regardless if thatcase
meets the criteria.
The following is an example of a single operation sequentialcase
statement, where four different values perform exactly the same.
const Animal = "Giraffe";switch (Animal) { case "Cow": case "Giraffe": case "Dog": case "Pig": console.log("This animal is not extinct."); break; case "Dinosaur": default: console.log("This animal is extinct.");}
The following is an example of a multiple-operation sequentialcase
clause, where, depending on the provided integer, you can receive different output. This shows you that it will traverse in the order that you put thecase
clauses, and it does not have to be numerically sequential. In JavaScript, you can even mix in definitions of strings into thesecase
statements as well.
const foo = 1;let output = "Output: ";switch (foo) { case 0: output += "So "; case 1: output += "What "; output += "Is "; case 2: output += "Your "; case 3: output += "Name"; case 4: output += "?"; console.log(output); break; case 5: output += "!"; console.log(output); break; default: console.log("Please pick a number from 0 to 5!");}
The output from this example:
Value | Log text |
---|---|
foo isNaN or not1 ,2 ,3 ,4 ,5 , or0 | Please pick a number from 0 to 5! |
0 | Output: So What Is Your Name? |
1 | Output: What Is Your Name? |
2 | Output: Your Name? |
3 | Output: Name? |
4 | Output: ? |
5 | Output: ! |
An alternative to if...else chains
You may often find yourself doing a series ofif...else
matches.
if ("fetch" in globalThis) { // Fetch a resource with fetch} else if ("XMLHttpRequest" in globalThis) { // Fetch a resource with XMLHttpRequest} else { // Fetch a resource with some custom AJAX logic}
This pattern is not doing a sequence of===
comparisons, but you can still convert it to aswitch
construct.
switch (true) { case "fetch" in globalThis: // Fetch a resource with fetch break; case "XMLHttpRequest" in globalThis: // Fetch a resource with XMLHttpRequest break; default: // Fetch a resource with some custom AJAX logic break;}
Theswitch (true)
pattern as an alternative toif...else
is especially useful if you want to utilize the fall-through behavior.
switch (true) { case isSquare(shape): console.log("This shape is a square."); // Fall-through, since a square is a rectangle as well! case isRectangle(shape): console.log("This shape is a rectangle."); case isQuadrilateral(shape): console.log("This shape is a quadrilateral."); break; case isCircle(shape): console.log("This shape is a circle."); break;}
Specifications
Specification |
---|
ECMAScript® 2026 Language Specification # sec-switch-statement |