switch case statement to control complex conditional operations.
switch case statement
switch statement is a flow-control statement that is similar to the
if else statement. You use the
switch statement to control the complex conditional operations.
The following illustrates the syntax of the
Each case in the
switch statement executes the corresponding statement (
statement_2,…) if the
expression equals the value (
break keyword causes the execution to jump out of the
switch statement. If you omit the
break keyword, the code execution falls through the original
case into the next one.
expression does not match any value, the
default_statement will be executed. It behaves like the
else block in the
The following flowchart illustrates the
You often use a
switch statement to replace a statement that consists of complicated
if else statements chained together. Basically, the
switch statement is equivalent to the following
if else statement.
switch case examples
The following example declares a variable named
day whose value represents a day in a week. The code outputs the name of the day based on the value of the
day variable by using the
In this case,
Tuesday is logged to the console window.
The following script demonstrates how the statements in a
switch block that falls through. It outputs the number of days in a month based on the input month and year.
How it works.
There are four cases:
- If the month is 1, 3,5, 7, 8, 10, or 12, the number of days in a month is 31.
- If the month is 4, 6, 9, or 11, the number of days in that month is 30.
- If the month is 2, and the year is not the leap year, the number of days is 28. If the year is the leap year, the number of days is 29.
- If the input month is not in the range, the script jumps the default branch and sets the
dayCountvariable to -1 that indicates the invalid month.
switch case statement to control complex conditional branching in the script.