Quackit Logo

FREE Hosting!

With every domain name you register with ZappyHost, you get FREE hosting.

$1.99 Domain Names

With every new non-domain purchase thru ZappyHost, you get a domain name for only $1.99.

JavaScript Switch Statement

Print Version

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.

<script type="text/javascript">
<!--
var myColor = "Red";

switch (myColor)
{
case "Blue":
	document.write("Just like the sky!");
	break
case "Red":
	document.write("Just like shiraz!");
	break
default:
	document.write("Suit yourself then...");
}
//-->
</script>

The resulting output:

Exlanation of code

We started by declaring a variable called "myColor" and setting it to "Red". We then opened a switch statement, passing in the variable we want to test (myColor). This is followed by a set of "cases" within curly braces. We add a "default" condition, which is only executed if none of the above cases are true. It's important to use "break" after each case - this prevents the code from running into the next case.

  1. We started by declaring a variable called "myColor" and setting it to "Red"
  2. We then opened a switch statement, passing in the variable we want to test (myColor)
  3. This 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.
  4. Prior to the closing bracket, we add a "default" condition, which is only executed if none of the above cases are true

Enjoy this website?

  1. Link to this page (copy/paste into your own website or blog):
  2. Add this page to your favorite social bookmarks sites:
               
  3. Add this page to your Favorites

Oh, and thank you for supporting Quackit!