For example, if the variable
myColor was equal to
Blue, we could output one message. If it is
Red we could output another, etc
Example Switch statement:
Here, we will re-write the last example in the previous lesson into a switch statement.
Exlanation of code
- When the user clicks any of the radio buttons, the
onclickevent handler calls the
analyzeColor()function. When we call that function, we pass in the value of the radio button (using
this.value). The function then takes that value and performs a
switchstatement on it.
- The switch statement's first line is
switch (myColor). This means that it will perform its tests against the value of the
- 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
defaultcondition is only executed if the other two aren't true (i.e. the selected color is neither Blue nor Red).