JavaScript switchStatement
JavaScript Statement Reference
Example
Display today's weekday name (Sunday=0, Monday=1, Tuesday=2, ...):
dayOutput:
Try it Yourself »
More examples are included at the bottom of this article.
Definition and Usage
The switch statement is used to perform different actions based on different conditions.
The switch statement is part of JavaScript's conditional statements, used to perform different actions based on different conditions. Use switch to select one of many blocks of statements to be executed.
The switch statement evaluates an expression. The value of the expression is then compared with the values of each case in the structure. If there is a match, the code block associated with that case is executed.
The switch statement is often used together with the break or default keyword. Both are optional:
breakThe keyword is used to break out of the switch code block. It terminates the execution of the switch code block. If this keyword is omitted, the next code block in the switch statement will be executed.
defaultThe keyword specifies what to do when there is no match. The default keyword can only appear once in a switch statement. Although it is optional, it is recommended to use it; in cases that are not what we expect, you can use it to output information.
Browser Support
| Statement | |||||
|---|---|---|---|---|---|
| switch | Yes | Yes | Yes | Yes | Yes |
Syntax
case n:
Code block
break;
case n:
Code block
break;
default:
Default code block
}
Parameter Values
| Parameter | Description |
|---|---|
| expression | Required. Specifies the expression to be evaluated. The expression is evaluated only once. The value of the expression is then compared with the values of each case in the structure. If there is a match, the code block associated with that case is executed. |
Technical Details
| JavaScript Version: | 1.2 |
|---|

More Examples
Example
If today is not Saturday and not Sunday, output the default message:
textOutput:
Try it Yourself »
Example
Sometimes you want different cases to use the same code. Or set a common default value.
Note that in the 3 cases, the cases use common code, and the default statement is not at the very end of the switch statement:
Try it Yourself »
Example
Use a switch statement to determine the content entered by the user:
Try it Yourself »
Related Pages
JavaScript Tutorial:JavaScript If...Else Statement
JavaScript Tutorial:JavaScript Switch Statement
JavaScript Reference:JavaScript if/else Statement
JavaScript Statement Reference Other Extensions