Quackit Logo
HTML
CSS
Scripting
Database
Hosting
Design
XML
IMCreator - Free Website Builder

JavaScript Switch Statement

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.

CodeResult

Favorite Color

Blue
Red
Green
None

Exlanation of code

  • When the user clicks any of the radio buttons, the onclick event 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 switch statement on it.
  • The switch statement's first line is switch (myColor). This means that it will perform its tests against the value of the myColor 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).

Enjoy this page?

  1. Link to this page (copy/paste into your own website or blog):
  2. Link to Quackit using one of these banner ads.

Thanks for supporting Quackit!