User Rating: 1 / 5

Star ActiveStar InactiveStar InactiveStar InactiveStar Inactive
 

Switch Statement is the one used in the program. Used in case we need to check conditions on several conditions. Which is similar to but different if ... else conditions Switch is used to check only once and then dismissed the case if I was to follow orders in the case , but if it does not match the case. would follow any command in the default condition if ... else it will be checked one by choice . If there are several options , it must be checked several times. Incommode

Syntax:

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

For example:

<html>
<body>
<p>Click the button to display what day it is today.</p>
<button onclick="myFunction()">Try it</button> 
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var d=new Date().getDay();
switch (d)
  {
  case 0:
    x="Today is Sunday";
    break;
  case 1:
    x="Today is Monday";
    break;
  case 2:
    x="Today is Tuesday";
    break;
  case 3:
    x="Today is Wednesday";
    break;
  case 4:
    x="Today is Thursday";
    break;
  case 5:
    x="Today is Friday";
    break;
  case 6:
    x="Today is Saturday";
    break;
  }
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>

 This the result:

 

 

Form of the command, the program will check the variable that the command switch (variable in brackets) that have a value of how much I used to check on the case if it matches the value of the case is reflected on the orders of the case. when finished, it will find the break resulted from the sudden switch in the absence of any values ​​that match the case specified program. To work in the default automatically. 

Example:

 <html>
<body>
<button onclick="myFunction()">Click Here</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var d=new Date().getDay();
switch (d)
  {
  case 6:
    x="Today is Saturday";
    break;
  case 0:
    x="Today is Sunday";
    break;
  default:
    x="Looking forward to the Weekend";
  }
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>

This is the result:

 

 

 

Next

Chapter 14 - JavaScript For Loop