js Switch

The switch statement in JavaScript is used to execute one block of code among multiple possible options. It provides a more readable and efficient way to handle multiple conditional branches compared to using multiple if-else-if statements. The switch statement evaluates an expression and matches the result with one of the case labels. When a match is found, the corresponding block of code is executed. If no match is found, the default block (if provided) is executed.

Syntax:

switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
// more cases...
default:
// code to be executed if no case matches
}

Example:

<script>
 var day = 3;

 switch (day) {
  case 1:
   console.log("Monday");
   break;
  case 2:
   console.log("Tuesday");
   break;
  case 3:
   console.log("Wednesday");
   break;
  case 4:
   console.log("Thursday");
   break;
  case 5:
   console.log("Friday");
   break;
  case 6:
   console.log("Saturday");
   break;
  case 7:
   console.log("Sunday");
   break;
  default:
   console.log("Invalid day");
   
 }
</script>

Output:

wednesday