Switch Statement in JavaScript | Use, Example

A switch statement in JavaScript is a multi-way decision statement that executes one statement from multiple conditions.

It uses the result of an expression to evaluate which statement has to be executed.

In other words, a switch statement executes statements based on the value of a variable or an expression, against a list of case values.

If a match found, a block of statements corresponding to that case has executed.

The switch statement is basically an enhanced version if-else if ladder statement. It is more convenient to use when there are multiple conditions or expressions in the code.

Syntax of Switch Statement in JavaScript


The general syntax of using the switch statement in JavaScript has as follows:

switch(expression)
{
    case value-1:
        // statement sequence
        break;
   case value-2:
      // statement sequence
      break;
   .
   .
   .
  case value-n:
       // statement sequence
       break;
  default:
        // default statement sequence
}
statement-x;

a) In the above switch syntax, an expression must be of integer, string, boolean, or character type. The expression must be type compatible with each of the values specified in the case statements. Duplicate case values have not permitted.

b) value-1, value-2, value-3, … are constants or literals. These constants have called case labels (or case clauses).

c) A switch can have multiple case clauses depending on requirements and must be unique within a switch statement. The case labels must end with a colon (:).

d) The statement sequence is a list of statements and may contain zero or more statements.

e) After each case, a break statement is necessary inside the switch block to come out from the switch block. Break statement terminates the loop.

f) The default statement is optional and execute when none of the previous cases matched. In other words, the default clause handles the case when no match of any case in the switch statement found.

How Switch statement works?


The flowchart of JavaScript switch statement for the selection process as shown in the below figure.

JavaScript switch statement flowchart diagram

JavaScript switch statement works as follows:

a) When the switch statement execute, the value of the expression has successively compared with each case value like value-1, value2-, …

b) If a match found, the statement sequence following that case label executed. For example, the value of expression is 1, then statements associated with case 1 will execute. Similarly, the value of expression is 2, statements associated with case 2 will execute.

c) If the value of expression does not equal to value-1, value-2, …., then none of the statement sequences will execute.
[adinserter block=”5″]
d) In this case, the default clause will execute, and then default statements will execute. However, the default statement is optional. If no case has matched and no default is present, then no further execution will take place.

e) The break statement has used inside the switch block to terminate statement sequences. It is optional. It immediately ends the switch statement.

f) When a break statement executes inside the switch block, the control of execution transfers to the next statement-x after the switch statement (skipping all the rest of case statements).

g) There is no need to use break statement in the default case, because default is the last case and after it, the switch statement will terminate.


Consider the following example.

let grade = prompt("Enter your grade").toUpperCase();
switch(grade)
{
  case 'A' :
      document.write("You got more than 80% marks.");
      break;
  case 'B' :
      document.write("You got more than 70% marks but less than 80.");
      break;
  case 'C' :
      document.write("You got more than 60% marks but less than 70.");
      break;
  case 'D' :
      document.write("You got more than 50% marks but less than 60.");
      break;
  default:
      document.write("You got less than 50% marks.");
}

Consider another very simple example.

let season = prompt("Enter the value for season: ").toUpperCase();
switch(season)
{
  case 'R' :
        document.write("Rainy season");
        break;
  case 'S' :
        document.write("Summer season");
        break;
  case 'W' :
        document.write("Winter season");
        break;
  case 'P' :
        document.write("Spring season");
        break;
  default:
        document.write("Invalid value for season");
}

Switch Statement Example Program for Best Practice


1. Let’s create a simple JavaScript program based on switch statement where we will execute a particular task depending on city value. We will take a variable city, and will assign a value d.

Depending on the city value, Mumbai will display when the value is m. Similarly, Dhanbad will display when the value is d; and so on. If city value is neither of the specified values: m, d, c, or r, then none of the statements will execute.
[adinserter block=”2″]
In this case, the default statement will execute, and it will display “Invalid city value”. Let’s write the code for it.

Program code 1:

<html>
<head>
      <title>Switch Statement Example Program</title>
</head>
<body>
<script>
// Declare a variable of char type.
    let city = 'd'; // Here, city is set to 'd'.
// Switch expression with char case values.
    switch(city)
   {
// Case statements.
        case 'm':
             document.write("Mumbai");
             break;
       case 'd':
             document.write("Dhanbad");
             break;
       case 'c':
             document.write("Chennai");
             break;
       case 'r':
             document.write("Ranchi");
             break;

// Default case statement.
       default:
             document.write("Invalid city value");
}
</script>
</body>
</html>
Output:
     Dhanbad

In this example program, since the city value is set to d, as a result, it will display “Dhanbad” as output and then the control will execute break statement which terminates the switch block.


2. Consider another example program in which we will take numeric case values inside the switch block. We will prompt the user to enter a number between 1 and 5. Based on the entered value, we will display one, two, three and so on.

Program code 2:

<html>
<head>
      <title>Switch...case Example Program</title>
</head>
<body>
<script>
// Variable hold a numeric value.
     let num = parseInt(prompt("Enter a number between 1 and 5: "));
     switch(num)
    {
      case 1:
         document.write("One");
         break;
      case 2:
         document.write("Two");
         break;
      case 3:
         document.write("Three");
         break;
      case 4:
         document.write("Four");
         break;
     case 5:
         document.write("Five");
         break;
     default:
         document.write("Invalid input");
}
</script>
</body>
</html>

While you will execute this program, a dialog box will appear on the screen. In this dialog box, you have to enter a numeric value. If you enter a numeric value 4, and the result will display four in the browser.

Output:
    Enter a number between 1 and 5:
    4
    Four

3. Let’s consider another example program in which we will pass a string value in the switch statement. In this case, the case labels must be string literal.

Program code 3:

<html>
<head>
     <title>Switch...case Example Program</title>
</head>
<body>
<script>
// Variable hold a string value.
    let gameLevel = "Intermediate";
    let level = 0;

// Passing string value in switch statement.
    switch(gameLevel) 
   {
// Using string literal in switch cases.
    case "Beginner": level = 1;
        break;
    case "Intermediate": level = 2;
        break;
    case "Expert": level = 3;
        break;
    default: level = 0;
        break;
  }
 document.write("Your game level is : " +level);
</script>
</body>
</html>
Output:
     Your game level is : 2

4. Let’s write a JavaScript program where we will not use break statements. As a result, it will execute all statements after the first match.

Program code 4:

<html>
<body>
<script>
    let num = 30;
    switch(num) 
   {
// Case statement without break statements.
     case 10: document.write("Ten", "<br>");
     case 20: document.write("Twenty", "<br>");
     case 30: document.write("Thirty", "<br>");
     case 40: document.write("Forty", "<br>");
     default: document.write("Default statement");
   }
</script>
</body>
</html>
Output:
     Thirty
     Forty
     Default statement

Nested Switch Statements in JavaScript with Example


Like nested if statements, we can also nest switch statements. That is, a switch can also be a part of the statement sequence of an outer switch. It is a nested switch.

When a switch statement placed within a case statement or default statement of another switch statement, it called nested switch in JavaScript.

The purpose of using nested switch statements in a program is to tell JavaScript interpreter to make another decision after the first decision.

Since a switch statement defines its own block, no conflicts occur between the case labels in the inner switch and those in the outer switch.


Consider the following example program to understand nested switch statements in JavaScript.

Program code 5:

<html>
<head>
     <title>JavaScript Nested Switch Statements Example</title>
</head>
<body>
<script>
// E - ECE, C - CS, I - Information Technology.
    let branch = 'E';
    let semester = 5;
    switch(branch) // Outer switch.
   {
     case 'E':
         switch(semester) // Inner switch
        {
           case 5:
             document.write("Microcontroller, Power Electronics, Analog circuit, Digital circuit");
             break;
        }
      break;

   case 'C':
       switch(semester) // Inner switch.
      {
         case 5:
           document.write("Java, Python, Data structure");
           break;
      }
    break;

   case 'I':
       switch(semester)
      {
        case 5:
            document.write("EDC, Java, Data structure, Microprocessor");
            break;
      }
   break;

  default:
         document.write("Invalid selection");
         break;
 }
</script>
</body>
</html>
Output:
     Microcontroller, Power Electronics, Analog circuit, Digital circuit

When to use Switch Statement?


The switch statement handles a series of decision in which a specific condition evaluates based on different values. You can use switch statement when you want to select one block out of multiple blocks of statements.

That is, use switch statement when you want to execute one statement depending upon multiple conditions. It is a better choice than JavaScript if-else-if ladder.

When you need to execute one statement out of two alternatives, use if-else statement.


In this tutorial, you learned switch statement in JavaScript with various example programs. Hope that you will have understood the basic concepts of switch statement and nested switch statements.
Thanks for reading!!!
Next ⇒ Loops in JavaScript⇐ PrevNext ⇒