Did you find this useful?
Socialize it today.


JavaScript Switch Statement

Tuesday, April 10, 2012

If you have experience with other programming languages, then you may already be familiar with the JavaScript switch statement and its purpose. If you are not yet familiar with its use, you will by the end of this tutorial. The switch statement was introduced in JavaScript 1.2, which is supported by all modern browsers, so you should have no issues integrating this statement into your routines. The switch statement is similar to the if...else if...else statement. However, it is much easier to use. Let us take a look at the syntax.


switch(expression)
{
case value1:
execute block of code
break;
case value2:
execute block of code
break;
default:
execute block of code if none of the cases produced a match.
}


While the syntax may not be self-explanatory, it is actually quite simple once you understand the concept. First, we start by using the switch statement along with an expression that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. The break statement is used to prevent the code from running into the next case automatically. If none of the cases produces a match, you can instruct JavaScript to execute the block of code after the default statement. Please note, if you are evaluating a string rather than an integer, make sure that you enclose the string with quotes. For example, case "string value":

Let's look at a quick and easy example that can easily take advantage of using the switch statement. In the following example, the button below the will generate an alert pop-up providing you with information about the current day of the week.


var d = new Date();
var today = d.getDay();
switch (today)
{
case 0:
alert("Today is Sunday.");
break;
case 1:
alert("Today is Monday.");
break;
case 2:
alert("Today is Tuesday.");
break;
case 3:
alert("Today is Wednesday, half way there!.");
break;
case 4:
alert("Today is Thursday.");
break;
case 5:
alert("Today is Friday. Ready for the weekend.");
break;
case 6:
alert("Today is Saturday!");
break;
default:
alert("I'm not sure what day it is today???");
}

In your HTML code...
<input type="button" onclick="show_alert()" value="Show me the Day!" />


Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

JavaScript and jQuery: The Missing Manual HTML CSS and JavaScript Editor Murachs JavaScript and DOM Scripting