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