Easy Tutorial
❮ Js Variables Js Operators ❯

JavaScript switch Statement


The switch statement is used to perform different actions based on different conditions.


JavaScript switch Statement

Use the switch statement to select one of many code blocks to be executed.

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 case 2
}

How it works: First, the expression n (usually a variable) is set. Then, the value of the expression is compared with the values of each case in the structure. If a match is found, the associated code block for that case is executed. Use break to prevent the code from automatically running into the next case.

Example

Display the name of the current day of the week. Note that Sunday=0, Monday=1, Tuesday=2, etc.:

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; 
}

Result for 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.write(x);

default Keyword

Use the default keyword to specify what to do if no match is found:

Example

If today is not Saturday or Sunday, a default message will be output:

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;

Result for x:

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.write(x);
❮ Js Variables Js Operators ❯