JavaScript Switch Statement

The Javascript switch statement will execute only one code block from many code blocks.

General Syntax
      switch (expression){
   case condition 1: statement(s)
   break;
   
   case condition 2: statement(s)
   break;
   ...
   
   case condition n: statement(s)
   break;
   
   default: statement(s)
}
    
Try it now

Source Code

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

Javascript Switch: The break Keyword

Javascript break keyword is an optional keyword that refers to the end of the case statements.

Source Code

          
            var weekname = "saturday";
switch (weekname) {
    case "monday":
        document.writeln("Monday, first day of the week..");
        break;
    case "tuesday":
        document.writeln("Tuesday, second day of the week..");
        break;
    case "wednesday":
        document.writeln("Wednesday, the third day of the week..");
        break;
    case "thursday":
        document.writeln("Thursday, the fourth day of the week..");
        break;
    case "friday":
        document.writeln("Friday, Fifth day of the week.");
        break;
    case "saturday":
        document.writeln("Saturday, Sixth day of the week and weekend.");
        break;
    case "sunday":
        document.writeln("Sunday, Seventh day of the week and weekend.");
        break;
    default:
        document.writeln("No any case found.");
}          
        
Try it now

Javascript Switch: The default keyword

The default keyword is used to specify the code to run if there is no switch case match.

Source Code

          
            switch (new Date().getDay()) {
  case 6:
    text = "Today is Saturday";
    break;
  case 0:
    text = "Today is Sunday";
    break;
  default:
    text = "Looking forward to the Weekend";
}          
        
Try it now

Multiple Cases

Multiple switch cases can be written inside the switch case. Let us take an example and understand it.

Source Code

          
            var data=3;
switch(data){
case 1: case 3: case 5: document.write("Odd no"); break;
case 2: case 4: case 6: document.write("Even no"); break;
default: document.write("No, not in range");
}          
        
Try it now

Web Tutorials

Javascript Switch Statement
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4