Switch Statement

switch statement is also used to check conditions in JavaScript like if else . Instead of using multiple if elses, we can use switch operator to check conditions as switch is faster in execution than if else and can also break operation once a condition is met.


How to use switch in javascript

Like other programming languages, switch is used in Javascript to test conditions. The comparing value is placed inside switch parentheses, after switch operator. Inside switch curly brackets, case keyword is used to test possible cases for switch value. After each case statement, the code that need to be run if that case is matched.

Break

After each case block, it is important to finish case with break keyword. The break keyword will stop any other case blocks being executed.

Default

default is used to show default output if all cases are failed.

Switch Example


        switch(x){
            case "1": output; break;
            case "2": output; break;
            default : output; break; 
        }
        

      var x=1;
      switch(x){
        case 1 : alert("Its One"); break;
        case 2 : alert("Its Two"); break;
        case 3 : alert("Its Three"); break;
        case 4 : alert("Its Four"); break;
        case 5 : alert("Its Five"); break;
        case 6 : alert("Its six"); break;
        case 7 : alert("Its seven"); break;
        default : alert("Invalid No);
      }
        

Switch Case Example

Check month name by using number.

:


      var month=n;  // from input above
      
      switch(month){
      case "1" : alert("Its Jan"); break;
      case "2" : alert("Its Feb"); break;
      case "3" : alert("Its Mar"); break;
      case "4" : alert("Its Apr"); break;
      case "5" : alert("Its May"); break;
      case "6" : alert("Its June"); break;
      case "7" : alert("Its July"); break;
      case "8" : alert("Its Aug"); break;
      case "9" : alert("Its Sept"); break;
      case "10" : alert("Its Oct"); break;
      case "11" : alert("Its Nov"); break;
      case "12" : alert("Its Dec"); break;
      default : alert("invalid month");
      }
        

Multiple Cases

Multiple Cases can also be used inside switch. Instead of writing same case again and again, it's better to use Multiple cases. Here is an example


var data=3;

switch(data){

case 1: case 3: case 5: console.log("odd no"); break;
case 2: case 4: case 6: console.log("even no"); break;
default: console.log("no not in range");

}