How to Use the Switch Statement in JavaScript

09/30/2021

Contents

In this article, you will learn how to use the switch statement in JavaScript.

Using the switch statement in JavaScript

The switch statement is a control structure in JavaScript that allows you to execute different blocks of code depending on the value of a variable. This is an alternative to using a series of if…else statements and can make your code more concise and easier to read.

Syntax

Here is the basic syntax for a switch statement:

switch (expression) {
  case value1:
    // code to be executed if expression matches value1
    break;
  case value2:
    // code to be executed if expression matches value2
    break;
  default:
    // code to be executed if expression doesn't match any values
    break;
}

The expression is the variable or value that you want to compare against the different cases. The case statements are the different values that you want to compare the expression against. If the expression matches a case value, the corresponding block of code will be executed. The break statement is used to exit the switch statement after the corresponding block of code has been executed.

The default statement is optional and is executed if none of the case statements match the expression.

Example

Here is an example of a switch statement that checks the day of the week:

let day = "Monday";
switch (day) {
  case "Monday":
    console.log("Today is Monday");
    break;
  case "Tuesday":
    console.log("Today is Tuesday");
    break;
  case "Wednesday":
    console.log("Today is Wednesday");
    break;
  case "Thursday":
    console.log("Today is Thursday");
    break;
  case "Friday":
    console.log("Today is Friday");
    break;
  default:
    console.log("It's the weekend!");
    break;
}

In this example, the switch statement checks the value of the day variable and executes the corresponding block of code. Since day is equal to “Monday”, the first block of code is executed, which logs “Today is Monday” to the console.

Tips for working with switch statements

Here are some tips for working with switch statements in JavaScript:

  • Be sure to include a break statement after each block of code. Otherwise, the switch statement will continue to execute the remaining blocks of code, which can lead to unexpected results.
  • You can use multiple cases for the same block of code by omitting the break statement. This can be useful if you want to execute the same code for multiple values.
  • The default statement is optional but can be useful for handling unexpected values or errors.
  • The expression that you pass into the switch statement can be any value, including variables or function calls.