Switch()

Creator:
Peter

The switch statement works like the if else statements but is more efficient when you need to test a the value of a variable. Take a look at both codes below, the first one uses the if else way, but the second one uses the switch way.

Example 1 - if else:

<script type="text/javascript"> 
<!-- 
var letter = "a"; 
if(letter == "a"){ 
    alert("Letter is A"); 
} else if(letter == "b"){ 
    alert("Letter is B"); 
} else if(letter == "c"){
    alert("Letter is C");
} 
//--> 
</script>

Example 2 - switch:
<script type="text/javascript"> 
<!-- 
var letter = "a"; 
switch(letter){ 
    case "a" : 
        alert("Letter is A"); 
        break; 
    case "b" : 
        alert("Letter is B"); 
        break; 
    case "c" : 
        alert("Letter is C"); 
        break; 
} 
//--> 
</script> 

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"> 
<!--
var letter = "a"; 
switch(letter){ 
    case "a" : 
        alert("Letter is A");
         break; 
    case "b" : 
        alert("Letter is B"); 
        break; 
    case "c" : 
        alert("Letter is C"); 
        break; 
    default :
        alert("Letter did not match");
 } 
//--> 
</script> 

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. So as you can see the switch statement can be very useful, I for one enjoy using it then do loads of if else statements. If you have a questions, feel free to post on the forum.

Description:
In this tutorial I cover the basic use of the switch() statement.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options