switch allows to executes different cases based on matched expression or condition.

Syntax

switch(condition)
{
 label:
  // set of statements
 break;
label:
  // set of statements
 break;
label:
  // set of statements
 break;
default
 // set of statements
}

Example

<script>
let month = 1;
switch(month)
{
case 1:
  document.write("January");
 break;
case 2:
 document.write("Febuary");
 break;
case 3:
 document.write("March");
 break;
case 4:
 document.write("April"); 
 break;
case 5: 
 document.write("May"); 
 break;
case 6: 
 document.write("June"); 
 break;
case 7: 
 document.write("July"); 
 break;
case 8:  
 document.write("August");  
 break;
case 9:  
 document.write("September");  
 break;
case 10:   
document.write("October");   
break;
case 11:   
document.write("November");   
break;
case 12:   
document.write("December");   
break;
default:
 document.write("Worng month number entered");
}
</script>

break keyword

In switch, case always ends with break keyword, because it stops execution of the very next case and execution control jumps out of switch block. It is optional

If multiple case needs to be executed then break statement can be omitted.

Example

<script>
let day = 1;
switch(day )
{
case 1:
  document.write("Monday");
 break;
case 2:
 document.write("Tuesday");
 break;
case 3:
 document.write("Wednesday");
 break;
case 4:
 document.write("Thrusday"); 
 break;
case 5: 
 document.write("Friday"); 
 break;
case 6: 
 document.write("Weekend"); 
case 7: 
 document.write("Weekend"); 
 break;
default:
 document.write("Worng day number entered");
}
</script>

In above example, break keyword is omitted in case 6, Hence both case 6 and case 7 gets executed.

default keyword

Default block statements executes when no cases matched.

default should be the last block, it is like else of if condition. when condition does not matches with any case, default block executes. and break is not used because default is last code block, so no need to write break statement.

<script>
let day = 1;
switch(day )
{
case 1:
  document.write("Monday");
 break;
case 2:
 document.write("Tuesday");
 break;
case 3:
 document.write("Wednesday");
 break;
default:
 document.write("Worng day number entered");
}
</script>

Switch with Multiple cases with common code or statement

javascript allows to use common code for multiple cases, if any case gets matched then statements get executed.

<script>
let time = 8;
switch(time)
{
case 8:
case 9:
case 10:
case 11:
case 12:
 document.write("Good Morning");
 break;
case 1:
case 2:
case 3:
case 4:
case 5: 
document.write("Good Afternoon"); 
break;
default:
 document.write("Good Night");
}
</script>