Saturday, April 30, 2011

JavaScript Switch Statement - XII


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:
Just like shiraz!

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

No comments:

Post a Comment