Switch Statement

Like if else ,switch statement is also used to check conditions in javascript. Instead of using multiplle if else, we can use switch operator.



How to use switch in javascript

Like other programmings, 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.

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

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(age){
      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");
      }