Advertise Here

Author Topic: Learn how to use the Switch() function  (Read 5930 times)

0 Members and 1 Guest are viewing this topic.

Offline slayer766

  • SMF For Free Full Member
  • *
  • Posts: 212
    • View Profile

  • Total Badges: 13
    Badges: (View All)
    Topic Starter Combination Level 3 Level 2 Level 1
Learn how to use the Switch() function
« on: February 04, 2008, 07:27:04 pm »
Switch functions are quite useful to you if you have a handful of statements to be executed from one variable or expression. They are basically if/else statements but compiled to a much better use. A switch function is set up as follows:


Code: [Select]
switch(variable){
case value1 :
code to be executed;
break;

case value2 :
code to be executed;
break;

default :
code to be executed if
}


Alright you always must start your function with the word switch() along with your variable in the parameter. This variable must be defined outside of this function for the function to work. The first case must have a value after it to determine how to initiate the first bit of code after it, being this is true or not, if it isn't then the next case will come up and match the value after and execute the specified code. You should always break after each code executed in the case because this prevents the code to execute onto the next case. Then if none of the values after each case match the variable in the parameter it turns down to default. That is what would be for your default action to be taken. Let me set up an example of a defined variable in action:


Code: [Select]
var TCZ = "Win";
switch(TCZ){
case "Win" :
alert("TCZ wins!");
break;

case "Lose" :
alert("TCZ lost!");
break;

default :
alert("TCZ has come to a draw!");
}

This bit of code will actually alert "TCZ wins!" it is because the variable "TCZ" has been defined to "Win". If I were to change the variable "TCZ" to "Lose" then it would skip over the first case and then execute the case with "Lose" and alert what I have in that case. If I were to change the variable to something other than "Win" or "Lose" then the switch function would skip down to default and execute what I have set up in default. :)

 

Related Topics

  Subject / Started by Replies Last post
14 Replies
3893 Views
Last post February 25, 2007, 12:08:08 pm
by Laugh-nd-kid
0 Replies
3972 Views
Last post February 04, 2008, 07:27:57 pm
by slayer766
0 Replies
3286 Views
Last post February 04, 2008, 07:28:49 pm
by slayer766
11 Replies
5208 Views
Last post July 17, 2008, 04:48:26 pm
by LaundryLady
1 Replies
7358 Views
Last post December 14, 2011, 10:30:04 pm
by SMF For Free