10X Sale
kh logo
All Courses
  1. Tutorials
  2. Web Development

Switch case

Updated on Sep 3, 2025
 
8,034 Views

Switch case can be used in the case of the if…else if…else statement. But it can only be used if all the if or else…if part depends on the value of a single variable.

Consider the below example of Javascript switch case.

var grade='D';
           switch (grade)
           {
              case 'A': console.log("Great Job");
              break;  
              case 'B': console.log("Pretty good");
              break;  
              case 'C': console.log("Passed");
              break;  
              case 'D': console.log("Just Passed");
              break;  
              case 'F': console.log("Failed");
              break;  
              default: console.log("Unknown Grade");
           }

// Just Passed

As we can see from the above example, the switch case depends on the value of a single variable i.e. grade. The grade can be A, B, C, D, F or some junk value entered by a user.
In the above example, we set the grade to D, so inside the switch statement case 'A', case 'B' and 'C' are checked and they are not true. Then when it encounters case 'D' it gets matched and Just Passed get prints. The break statement after that is very important as it stops the further execution of switch and it breaks or comes out of it. So, case 'F' and default statements won’t be checked.

To check the importance of break, let’s remove it from case 'D' and case 'F' in the above example and run it. You can see in the output that all three console log of Just Passed, Failed and Unknown Grade get printed

var grade='D';
           switch (grade)
           {
              case 'A': console.log("Great Job");
              break;   
              case 'B': console.log("Pretty good");
              break;   
              case 'C': console.log("Passed");
              break;   
              case 'D': console.log("Just Passed");
              case 'F': console.log("Failed");
              default: console.log("Unknown Grade");
           }
// Just Passed
// Failed
// Unknown Grade

We can use the above logic of break to our advantage, to create some cases which just pass through. Suppose in the above example, we want grade A, B, C to print Good Job and grade D and F to print Bad Job. We can do it by below.

var grade='D';
           switch (grade)
           {
              case 'A':   
              case 'B':    
              case 'C': console.log("Good Job");
              break;   
              case 'D':   
              case 'F': console.log("Bad Job");
              break;
              default: console.log("Unknown Grade");
           }
// Bad Job
+91

By Signing up, you agree to ourTerms & Conditionsand ourPrivacy and Policy

pattern
10% OFF
Coupon Code "TEN10"
Coupon Expires  17/11
Copy
Get your free handbook for CSM!!
Recommended Courses