JavaScript Switch Statement

JavaScript switch statement is same as if..else if..else statement, but switch statement only focus which condition is true and only that code of block execute, will not check for other condition whether they are satisfied or not as if..else if statement

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
}

 

Example:

var day=new Date().getDay();
switch (day)
{
case 0:
  x="Today it's Sunday";
  break;
case 1:
  x="Today it's Monday";
  break;
case 2:
  x="Today it's Tuesday";
  break;
case 3:
  x="Today it's Wednesday";
  break;
case 4:
  x="Today it's Thursday";
  break;
case 5:
  x="Today it's Friday";
  break;
case 6:
  x="Today it's Saturday";
  break;
}

 

Leave a Reply