Path: blob/main/files/en-us/web/javascript/reference/statements/switch/index.md
6520 views
------{{jsSidebar("Statements")}}
The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered. The default clause of a switch statement will be jumped to if no case matches the expression's value.
{{EmbedInteractiveExample("pages/js/statement-switch.html", "taller")}}
Syntax
expression: An expression whose result is matched against each
caseclause.
case valueN{{optional_inline}}: A
caseclause used to match againstexpression. If theexpressionmatches the specifiedvalueN(which can be any expression), execution starts from the first statement after thatcaseclause until either the end of theswitchstatement or the first encounteredbreak.
default{{optional_inline}}: A
defaultclause; if provided, this clause is executed if the value ofexpressiondoesn't match any of thecaseclauses. Aswitchstatement can only have onedefaultclause.
Description
A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using the strict equality comparison) and transfers control to that clause, executing all statements following that clause.
The clause values are only evaluated when necessary — if a match is already found, subsequent case clause values will not be evaluated, even when they will be visited by fall-through.
If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing statements following that clause. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so. A switch statement may only have one default clause; multiple default clauses will result in a {{jsxref("SyntaxError")}}.
Breaking and fall-through
You can use the break statement within a switch statement's body to break out early, often when all statements between two case clauses have been executed. Execution will continue at the first statement following switch.
If break is omitted, execution will proceed to the next case clause, even to the default clause, regardless of whether the value of that clause matches. This behavior is called "fall-through".
You can use other control-flow statements to replace break, such as a return statement.
Lexical scoping
The case and default clauses are like labels: they indicate possible places that control flow may jump to. However, they don't create lexical scopes themselves (neither do they automatically break out — as demonstrated above). For example:
This example will output the error "Uncaught SyntaxError: Identifier 'message' has already been declared", because the first const message = 'hello'; conflicts with the second const message = 'hi'; declaration, even when they're within their own separate case clauses. Ultimately, this is due to both const declarations being within the same block scope created by the switch body.
To fix this, whenever you need to use let or const declarations in a case clause, wrap it in a block.
This code will now output hello in the console as it should, without any errors.
Examples
Using switch
In the following example, if expr evaluates to Bananas, the program matches the value with case case 'Bananas' and executes the associated statement. When break is encountered, the program breaks out of switch and executes the statement following switch. If break were omitted, the statement for the case 'Cherries' would also be executed.
Putting the default clause between two case clauses
If no match is found, execution will start from the default clause, and execute all statements after that.
It also works when you put default before all other case clauses.
Taking advantage of fall-through
This method takes advantage of the fact that if there is no break below a case clause, execution will continue to the next case clause regardless if that case meets the criteria.
The following is an example of a single operation sequential case statement, where four different values perform exactly the same.
The following is an example of a multiple-operation sequential case 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 the case clauses, and it does not have to be numerically sequential. In JavaScript, you can even mix in definitions of strings into these case statements as well.
The output from this example:
| Value | Log text |
|---|---|
foo is NaN or not 1, 2, 3, 4, 5, or 0 | 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 of if...else matches.
This pattern is not doing a sequence of === comparisons, but you can still convert it to a switch construct.
The switch (true) pattern as an alternative to if...else is especially useful if you want to utilize the fall-through behavior.
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
{{jsxref("Statements/if...else", "if...else")}}