|
| |
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;
}
| |
| Subscribe |
|
Submit your email address and receive
article and product notifications. Your email is safe with us.
|
|
|
|