The switch statement works like the if else statements but is more efficient when you need to test the value of a variable.
Take a look at both codes below, the first one uses the if else way, the second one uses the switch way.
<script type="text/javascript">
|
|
<script type="text/javascript">
|
|
Both scripts do exactly the same thing, only that the switch statement works by feeding the variable in and looks at the labels to see if there is a match. So instead of doing == to test the variable, you do case "XX" where XX would be the value to test against. With the labels you need to terminate each one by using the "break" keyword, otherwise it will just skip that test on the variable. You can build up complex switch statements to run functions and perform other tasks.
Ok, so you have your switch statement testing a variable for a specific value, what if none of the tests match, and you want to allow for a default task to be performed if that is the case? Simple, we will use the "default" label to do this for us. Have a look at the example below, the script is exactly the same as above but we have included a default label to perform a task if all the matches return false.
<script type="text/javascript">
|
|
With the above script we added the default label, so that at least something will get displayed. So if the variable "letter" does not match "a", "b", or "c", then it will alert the message "Letter did not match". If you notice with the default label, you do not need to provide the "break" keyword. I have one little trick for you that can come in handy. First, lets have a look at some example code, then I will explain it.
<script type="text/javascript">
|
|
Can you see the difference? Nope? Well, have a look at the second test, which is testing for the letter "b". If you notice, the "break" keyword has been missed off, and no, it wasn't a mistake, because what is happening is if the the test for the letter "a" returns false, then it moves to the next label to see if there is a match, but what it is doing is doing an "OR" match. So if the variable "letter" is not "a", it is then checked to see if the letter is either "b" or "c", if it matches any of those two labels, you will get the alert message "Letter is not A". The switch statement above is equal to the if/else if/else statements below.
<script type="text/javascript">
|
|
So as you can see the switch statement can be very useful, I for one enjoy using it rather than doing loads of if else statements.
| Discuss Tutorial: Using the Switch Statement | 0 Comments |