How to Use the Switch Statement in JavaScript



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.


Here is the basic syntax for a switch statement:

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

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.


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");
  case "Tuesday":
    console.log("Today is Tuesday");
  case "Wednesday":
    console.log("Today is Wednesday");
  case "Thursday":
    console.log("Today is Thursday");
  case "Friday":
    console.log("Today is Friday");
    console.log("It's the weekend!");

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.