Thursday, June 21, 2012

Java Script Tutorial 9 : JavaScript Switch Statement


The switch statement are used to perform different action based on different conditions. The switch statement can be replaced by performing many if-then-else-if conditions, but when the answer of an evalution can give you many different answers, the switch-case statement can be more efficient. Syntax of switch statement is as follow :


switch(x)
{
case 1:
  execute code block 1
  break;
case 2:
  execute code block 2
  break;
default:
  code to be executed if x is different from case 1 and 2
}


The value of the variable x will be 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. Use break to prevent the code from running into the next case automatically. For example


switch ( day )
{
case 0:
  y="Sunday";
  break;
case 1:
  y="Monday";
  break;
case 2:
  y="Tuesday";
  break;
}


If the value of variable day is 0 then result will be "Sunday", and result will be "Monday" and "Tuesday" if values will be 1 and 2 respectively.


We use the default keyword to specify what to do if there is no match. For example, there is no value equal to 0, 1 or 2, then write a default message, for example write "friday".


switch ( day )
{
case 0:
  y="Sunday";
  break;
case 1:
  y="Monday";
  break;
case 2:
  y="Tuesday";
  break;
default:
  y="Friday";
}


If there is no match found then result will be "friday".

No comments:

Post a Comment