JavaScript Switch Statement
The Switch statement can be used in place of the If statement when you have many possible conditions.
In the previous lesson about JavaScript If statements, we learned that we can use an If Else If statement to test for multiple conditions, then output a different result for each condition.
For example, if the variable myColor
was equal to Blue
, we could output one message. If it is Red
we could output another, etc
Another way of doing this is to use the JavaScript Switch statement. An advantage of using the switch statement is that it uses less code, which is better if you have a lot of conditions that you need to check for.
Example Switch statement:
Here, we will re-write the last example in the previous lesson into a switch statement.
Explanation of code
- When the user clicks any of the radio buttons, the
onclick
event handler calls theanalyzeColor()
function. When we call that function, we pass in the value of the radio button (usingthis.value
). The function then takes that value and performs aswitch
statement on it. - The switch statement's first line is
switch (myColor)
. This means that it will perform its tests against the value of themyColor
variable. - This line is followed by a set of "cases" within curly braces. It's important to use "break" after each case - this prevents the code from running into the next case. In the case of the color being Blue, it displays an alert box with a message customized to that color. The same for Red. The
default
condition is only executed if the other two aren't true (i.e. the selected color is neither Blue nor Red).