JavaScript Switch

JavaScript Switch statement is used to execute different set of statements based on different conditions. It is similar to If-Else statement, but excels in code simplicity and works greatly with numbers, characters and Strings.

Syntax

switch(expression){
    case value_1 : 
      // set of statements
      break;
    case value_2 : 
      // set of statements
      break;
    default : 
      // set of statements
  }
Try Online

Explanation: The switch expression is evaluated and each case value is matched against it. When there is a match for a case value, the corresponding set of statements are executed.

  • break statement is must, for each case block, for desired conditional execution.
  • default block is executed when no case value is matched.

Example 1 – JavaScript Switch

<script>
  var value=2;
  var message='';
  switch(value){
    case 1:
  	  message += "Value is 1.";
  	  break;
    case 2:
  	  message += "Value is 2.";
      message += " This is second statement.";
  	  break;
    case 3:
  	  message += "Value is 3.";
  	  break;
    default :
  	  message += "Value is default."
  }
  document.getElementById("message").innerHTML = message;
</script>
Try Online

Try Online

Note: Please note that there is break statement at the end of every case block. Failing to provide a break statement results in not breaking of switch statement. This makes the subsequent case blocks executed. Following is an example demonstrating such scenario, where break is not used for case blocks in switch statement.

<script>
  var value=2;
  var message='';
  switch(value){
    case 1:
  	  message += "Value is 1.";
    case 2:
  	  message += "Value is 2.";
      message += " This is second statement.";
    case 3:
  	  message += " Value is 3.";
    default :
  	  message += " Value is default."
  }
  document.getElementById("message").innerHTML = message;
</script>
Try Online

Try Online

Conclusion

In this JavaScript Tutorial, we have learnt the syntax and working of JavaScript Switch statement with examples and possible pitfalls.