The switch
statement can make several comparisons at once. It's functions the exact same way as using multiple if
, if-else
, and else
statements. If you have many possible outcomes and want to shorten your code or make it more readable, using the switch
statement is recommended. It selects the statements executed based on the value of the switch
expression and the case.
The first thing a switch
statement does is it evaluates the expression. This expression can be of any data type, including numbers, objects, strings, etc. When one of the constants specified in a case label is equal to the expression, the statement that corresponds to that case is executed. If none of the cases are equal to the expression, the default case is executed if it exists. Otherwise, nothing is executed.
The example above prints the days of the week based on the value of the variable day
. Each case label has a number from 1-7 that prints the corresponding day. The default case is only executed if and only if the value of day
is not between 1 and 7. The break;
statement exists in each case for a good reason, and will be explored in the next card. For the time being, try to visualize how the switch
statement works and how it can be used in more complex programs such as a calculator or a game.