JavaScript Switch Case – A Complete Guide

Switch case came in handy when a huge amount of choices are present in a problem and repeated if-else statements make the code lengthy and difficult to read. In JavaScript, we can use a switch case to branch out in multiple directions based on different conditions. It is a more efficient and self-explanatory selection control mechanism than multiple if statements.

It uses search and map techniques to allow variables to change the control flow of a particular block of code or program. The word “switch” is used because this technique shuffles between choices based on required needs, such as switching the light on when you enter a dark room but keeping the other switches off to save electricity.

Also Read: JavaScript Strict Mode: What it Does and Doesn’t Allow

Switch Case Flowchart

This method of choosing from a variety of options is like choosing your dinner from a menu card at a restaurant. Whatever you choose, your bill will be calculated accordingly; hence we can represent the switch case in a flowchart where different statements are executed upon the fulfillment of certain conditions. Using a flowchart, a switch case conditional flow can be shown below:

Flowchart Expression
flowchart.

Syntax of Switch Case

The way that the execution occurs is given below which is then followed by the syntax of the switch case control flow system:

  • The switch expression evaluation occurs only once.
  • Then the comparison between the given expression and all the present statement cases is carried out.
  • The case that matches the given value of the expression is executed.
  • The break; statement at the end of every case ensures that the control exits the switch statement after executing the required case.
  • In case there are multiple matches, only the first case is executed.
  • In case there are no matches found in the entire switch case section, the default case is executed.
  • The default case doesn’t have to be the last case every time, it can be written in the beginning as well.
  • In case there are no default cases and no possible matching cases, the control is passed on to the next code block and the statement after the switch case is executed.
switch(expression) {
  case A:
    // code block
    break;
  case B:
    // code block
    break;
  .
  .
  .
  .
  .
  case N:
    // code block
    break;
  default:
    // code block
}

Examples demonstrating Switch case in JavaScript

1st Example:

In the first example, we find the remark associated with a particular grade. The code is used in a school system to find out the correct remark for a particular grade in the range from ‘a’ to ‘f’, any other letter is not recognized as a grade. Here, the “grade_of_student” variable represents the grade received by a student and has been already assigned a value of ‘a’. The remarks associated with the letters are :

  • ‘a’: Excellent!!
  • ‘b’: Good!
  • ‘c’: Passed.
  • ‘d’: Barely passed.
  • ‘f’: Failed.
  • The default case would be: grade not recognized.

The code for the above example:

            var grade_of_student = 'a';
            document.write("The remark associated with the grade is: <br />");
            switch (grade) 
            {
               case 'a': 
                document.write("Excellent!!<br />");
                break;
            
               case 'b': 
                document.write("Good!<br />");
                break;
            
               case 'c': 
                document.write("Passed.<br />");
                               break;
            
               case 'd': document.write("Barely passed.<br />");
               break;
            
               case 'f': document.write("Fail.<br />");
               break;
            
               default:  document.write("grade not recognized<br />")
            }

The output for the above code would be:

The remark associated with the grade is
Excellent!!
Switch Case Example-1
The code and the output of the first example.

2nd Example:

Keeping the remarks fixed from the previous example, now, we will take the grade as input from the user and then display the result according to the given user input. Let’s look at the code for the same:

          var grade = prompt("What is your grade?");
            document.write("You entered the grade:");
            document.write(grade);
            document.write("<br />");
            document.write("The remark associated with the grade is <br />");
            switch (grade) 
            {
               case 'a': 
                document.write("Excellent!!<br />");
                break;
            
               case 'b': 
                document.write("Good!<br />");
                break;
            
               case 'c': 
                document.write("Passed.<br />");
                               break;
            
               case 'd': document.write("Barely passed.<br />");
               break;
            
               case 'F': document.write("Fail.<br />");
               break;
            
               default:  document.write("grade not recognized<br />")
            }

A pop-up box will appear where you will be prompted to enter your grade, in this case, I used the ‘b’ grade as input.

Switch Case Example-2 Output
Input prompt for user

The output of the following code would be something as shown below:

You entered the grade:b
The remark associated with the grade is
Good!
Switch Case Example-2
The code and the output of the 2nd example.

Conclusion

Switch case is a powerful control flow mechanism that makes multiple-choice problems easier and more compact than lengthy if-else statements or other alternatives. It is one of the most popular statements and is extremely easy for beginners to navigate between code blocks which has more than 2 or 3 alternatives. Javascript is one of the most popular in today’s world and also contains this mechanism for a smooth user experience. Hope this tutorial helps you to understand the concept of Switch Case in JavaScript.

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

Shreya Bose
Shreya Bose
Articles: 2