Switch Statement

switch statement is also used to control code flow or 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 the condition is met. break keyword is used to stop further execution and checking cases.


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


       const x=2;

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

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

Switch Case Example

Check month name by using number.

:


      const console.logmonth=n;  // from input above
      
      switch(month){
      case "1" : console.log("Its Jan"); break;
      case "2" : console.log("Its Feb"); break;
      case "3" : console.log("Its Mar"); break;
      case "4" : console.log("Its Apr"); break;
      case "5" : console.log("Its May"); break;
      case "6" : console.log("Its June"); break;
      case "7" : console.log("Its July"); break;
      case "8" : console.log("Its Aug"); break;
      case "9" : console.log("Its Sept"); break;
      case "10" : console.log("Its Oct"); break;
      case "11" : console.log("Its Nov"); break;
      case "12" : console.log("Its Dec"); break;
      default : console.log("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


const 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");

}