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;

   } 
Output
value of i = 2
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;
   }
Output is here

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>

Without break;

<script type="text/javascript">
var str='';
var opt=5;

switch (opt) 
   {
case 5:
str = str + ' equal to  5 '
case 8:
str = str + ' equal to  8'
case 10:
str = str + ' equal to  10 '
break;

default:
str = str + ' No matching '
break;
   }
 document.write(str);  
</script>


plus2net.com




Post your comments , suggestion , error , requirements etc here .




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer