Categories:
Partners

The switch statement of JavaScript

If you work with additional programming languages besides JavaScript (such as C++), then you probably already know exactly what the switch statement is and how to use it. For everyone else whose only encounter with a "switch" has been the one on the wall, it's about time you get acquainted with this useful programming "thingie". Note that the switch statement was introduced to JavaScript starting in JavaScript1.2, which is supported by all modern browsers.

The switch statement is basically an enhanced version of the "if-else" statement that is more convenient to use when you have code that needs to choose a path from many to follow. Let's have a look at this statement's general syntax:

Syntax: Example:

switch (expression){
case value1:
statement;
break;
case value2:
statement;
break;
"
"
default : statement;
}

switch (favoritemovie){
case "Titanic":
alert("Not a bad choice!")
break;
case "Water World":
alert("No comment")
break;
case "Scream 2":
alert("It has its moments")
break;
default : alert("I\'m sure it was great");
}

Ok, not exactly self-explanatory, but it's actually quite simple. The switch statement always begin with the keyword "switch", plus a required parameter that contains the expression (or variable) you wish to evaluate. This expression is then matched against the value following each "case", and if there is a match, it executes the code contained inside that case. If no match is found, it executes the default statement at the end of the switch statement. In the example code on the right, variable "favoritemovie" contains the name of a surfer's favorite movie. If his selection happens to be either "Titanic", "Waterworld", or "Scream 2", a customized message is alerted. All other selections will simply result in a generic, "I'm sure it was great" message.

A switch statement is essentially the same as a series of "if" and "else-if" statements. "So, what's the point of even having a switch statement", you may ask. Well, it's simple to use, logical in syntax, and most importantly, many programmers swear by it. You don't have to adopt it when writing conditional statements; in fact, you won't even notice a difference. But as my old science teacher used to say "Try it, you'll like it!"

The follow uses the switch statement to create a "redirection" script based on the day of the week:

<script type="text/javascript">
var dateobj=new Date()
var today=dateobj.getDay()
switch(today){
case 1:
window.location="monday.htm"
break
case 2:
window.location="tuesday.htm"
break
case 3:
window.location="wednesday.htm"
break
case 4:
window.location="thursday.htm"
break
case 5:
window.location="friday.htm"
break
case 6:
window.location="saturday.htm"
break
case 0:
window.location="sunday.htm"
break
}
</script>