Javascript Switch

This conditional statement  is used to execute one code from multiple expressions. It is just like else if statement that we have learned in previous page. But it is convenient than if..else..if because it can be used with numbers, characters etc.

Syntax:-
switch(expression){  
	case value1:  
   code to be executed;  
   break;  
 case value2:  
   code to be executed;  
   break;  
   ......  
  default:   
    code to be executed if above values are not matched;  
}    

Let’s see the simple example of switch statement in javascript.

Input:-
 <script>  
	   var grade='A';  
    var result;  
    switch(grade){  
    case 'A':  
       result="A Grade"; 
    case 'B':  
        result="B Grade";  
    case 'C':  
        result="C Grade";  
    case 'D':  
        result="D Grade";  
    }  
    document.write(result);
</script>

Output:-

Now it is not checking the condition mentioned in switch statement, it is only executing the last statement. To overcome this situation, we have break keyword.


Break keyword

Break keyword help in stop the execution inside the switch block.

It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.

Input:-
 <script>  
	   var grade='A';  
    var result;  
    switch(grade){  
       case 'A':  
         result="A Grade"; 
         break;
       case 'B':  
          result="B Grade";  
          break;
       case 'C':  
          result="C Grade";  
          break;
       case 'D':  
          result="D Grade";  
          break;
     }  
     document.write(result);
</script>

Output:-


Default keyword

Now if no case is matched in switch condition, it needs a default statement to be executed.

Input:-
 <script>  
	   var grade='E';  
    var result;  
    switch(grade){  
       case 'A':  
         result="A Grade"; 
         break;
       case 'B':  
          result="B Grade";  
          break;
       case 'C':  
          result="C Grade";  
          break;
       case 'D':  
          result="D Grade";  
          break;
	      default:
          result="No Grade matched";
     }  
     document.write(result);
</script>

Output:-


Grouping of case

Several variants of case which share the same code can be grouped.

Input:-
 <script>  
	   var a = 2 + 2;  
    var result;  
    switch(a){  
       case 2:
       case 3:  
          result="Too small!"; 
          break;
       case 4:  
          result="Exactly!";  
          break;
       case 5: 
       case 6: 
          result="Too big!";  
          break;
       default:
          result="I don't know such values";
     }  
     document.write(result);
</script>

Output:-