SQL PHP HTML ASP JavaScript articles and free scripts to download
 

JavaScript switch statement

Switch statement is used as an alternate to multiple if .. else statements. When we know various or more possibilities are to be tested then switch statement is an efficient way to do coding.

Switch statement is used in different requirements and is similar to many PHP switch and ASP switch statements.

The syntax is like this

switch(expression)
{
case value:
expression;
break;

case value:
expression;
break;

default:
Expression;

}

Now let us try with an example

var i=2;
switch (i)
{
case 1:
document.write ("value of i = 1");
break;

case 2:
document.write ("value of i = 2");
break;

case 3:
document.write ("value of i = 3");
break;

default:
document.write ("value of i is not equal to any given values");
break;
}

Now we will using switch statement display the today's day. To know the day we will use getDay() function. Here it is

var my_day=new Date()
var today=my_day.getDay();

switch (today)
{
case 0:
document.write ("Today is Sunday");
break;
case 1:
document.write ("Today is Monday");
break;

case 2:
document.write ("Today is Tuesday");
break;

case 3:
document.write ("Today is Wednesday");
break;

case 4:
document.write ("Today is Thursday");
break;

case 5:
document.write ("Today is Friday");
break;

case 6:
document.write ("Today is Saturday");
break;

default:
document.write ("value of i is not equal to any given days");
break;
}

switch with string variable

Here is an example by using a string variable with switch statement

<script language='JavaScript' type='text/JavaScript'>
var text="Hello"; // Assigned a value to the variable text
switch (text) // Passing the variable to switch condition
{
case "Hello 1":
document.write ("Hello 1");
break;

case "Hello 2":
document.write ("Hello 2 ");
break;


case "Hello":
document.write ("Correct Text Hello ");
break;

default:
document.write ("This is default selection");
break;
}
</script>




Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked


Join Our Email List
Email:  
For Email Newsletters you can trust
Basic Loops