Switch Statement in JavaScript

1.  Purpose
  • The switch statement provides a more concise way to execute different blocks of code based on different values of a single expression. It’s like a multi-way if…else.
2. Syntax
switch(expression) {
case value1:
// Code to be executed if expression === value1
break;
case value2:
// Code to be executed if expression === value2
break;
case value3:
// Code to be executed if expression === value3
break;
// ... more cases
default:
// Code to be executed if none of the cases match
}
  • expression: The value to be evaluated.
  • case value1: Represents a possible value for the expression.
  • break; Crucial! It prevents the code from falling through to the next case even if it matches.
  • default: (Optional) This block is executed if none of the case values match the expression.
3. Example:
let day = "Sunday";
switch (day) {
case "Monday":
console.log("It's Monday!");
break;
case "Tuesday":
console.log("It's Tuesday!");
break;
case "Wednesday":
console.log("It's Wednesday!");
break;
// ... more cases
case "Sunday":
console.log("It's the weekend!");
break;
default:
console.log("It's another day.");
}

In this example:

  • The switch statement checks the value of the day variable.
  • Since the day is “Sunday”, the code in the case “Sunday” block will execute, and “It’s the weekend!” will be printed to the console.
Scroll to Top