JavaScript Switch statement

The `switch` statement in JavaScript is used to perform different actions based on different conditions. It is an alternative to using multiple `if-else-if` statements when you have a large number of conditions to check. The `switch` statement evaluates an expression and compares its value to different cases. If a matching case is found, the corresponding code block is executed.

Here's the syntax for a `switch` statement:

switch (expression) {
  case value1:
    // code to be executed if expression === value1
  case value2:
    // code to be executed if expression === value2
    // code to be executed if none of the cases match

An example of using a `switch` statement to determine the name of a day based on its number:

const day = 3;
let dayName;

switch (day) {
  case 0:
    dayName = "Sunday";
  case 1:
    dayName = "Monday";
  case 2:
    dayName = "Tuesday";
  case 3:
    dayName = "Wednesday";
  case 4:
    dayName = "Thursday";
  case 5:
    dayName = "Friday";
  case 6:
    dayName = "Saturday";
    dayName = "Invalid day number";

console.log(dayName); // "Wednesday"

In this example, the `switch` statement evaluates the value of `day` and compares it to each case. When it finds a matching case (in this case, `day` is equal to 3), it executes the corresponding code block and sets the value of `dayName` accordingly. The `break` statement is used to exit the `switch` statement after a match is found, preventing the execution of the remaining cases. If no matching case is found, the code block in the `default` case is executed.

The `switch` statement can make your code more readable and efficient when dealing with a large number of conditions. However, it's important to remember to include the `break` statement in each case to prevent unintended behavior.

Was this page helpful?