Loading

Switch statement

  • In JavaScript, the switch statement is a control structure that allows to execution of different blocks of code based on the value of an expression.
  • It is commonly used when you have multiple possible conditions to test against a single value.

Syntax:

switch (expression) {
   case value1:
       break;
   case value2:
       break;
   // Add more cases as needed
   default:    
}

Example:

<!DOCTYPE html>
<html>
<body>
   <script>
      var grade = 'B';
      var result;
      switch (grade) {
         case 'A':
            result = "A Grade";
            break;
         case 'B':
            result = "B Grade";
            break;
         case 'C':
            result = "C Grade";
            break;
         default:
            result = "No Grade";
      }
      document.write(result);  
   </script>
</body>
</html>

Output:

B Grade