What is Switch...case statement in JavaScript?

JavascriptWeb DevelopmentFront End Technology

The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.

You can use a switch statement which handles exactly this situation, and it does so more efficiently than repeated if...else if statements.

Syntax

switch(expression) {
   case condition 1:statement(s)
   break;
   
   case condition 2:statement(s)
   break;
   ...
   
   case condition n:statement(s)
   break;
   
   default:statement(s)
}

The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases.

Example

You can try to run the following to learn how to work with switch case statement in JavaScript −

Live Demo

<html>
   <body>
      <script>
         var grade = 'A';
         document.write("Entering switch block<br />");
         switch(grade) {
            case'A': document.write("Good job <br />");
            break;

            case'B': document.write("Pretty good <br />");
            break;

            case'C': document.write("Passed <br />");
            break;

            case'D': document.write("Not so good <br />");
            break;

            case'F': document.write("Failed <br />");
            break;

            default:  document.write("Unknown grade<br />")
         }
         document.write("Exiting switch block");
      </script>
   </body>
</html>
raja
Published on 19-Jan-2018 06:16:43
Advertisements