Switch Statements in JavaScript

By Chris Minnick, Eva Holland

Switch statements in JavaScript are like highways with many different exits. The switch statement chooses among multiple cases by evaluating an expression. These values are like the exits. Each of these values in a switch statement is called a case.

The switch statement starts with the switch keyword, followed by an expression in parentheses and then a series of different options (called cases).

The syntax for the switch statement looks like this:

switch (expression) {
  case value1:
    //statements to execute
    break;
  case value2:
    //statements to execute
    break;
  case default:
    //statements to execute
    break;
}

You can have as many cases inside a switch statement as you’d like. The switch statement will try to match the expression to each case until it finds one that matches. Then it runs the statements within that case until it gets to the break statement, which causes it to exit the switch statement. Each case must end with a break statement or semicolon (;). This tells the program to do everything inside the case up until the break statement and then stop.

A default case will run if no case matches the result of the expression.

Take a look at an example! The code shown here asks the user to enter his favorite day of the week. The program then uses a switch statement to produce a different output based on possible values that the user might enter. If the user enters anything other than a day of the week, the default switch statement will run.

var myNumber = prompt("Enter your favorite day of the week!");
var theResponse;
switch (myNumber) {
  case "Monday":
    theResponse = "Ack!";
    break;
  case "Tuesday":
    theResponse = "Taco day!";
    break;
  case "Wednesday":
    theResponse = "Halfway there!";
    break;
  case "Thursday":
    theResponse = "It's the new Friday!";
    break;
  case "Friday":
    theResponse = "TGIF! Yeah!";
    break;
  case "Saturday":
    theResponse = "What a day!";
    break;
  case "Sunday":
    theResponse = "Sunday = Funday!";
    break;
  default:
    theResponse = "I haven't heard of that one!";
    break;
}
alert (theResponse);

Follow these steps to try out this program in JSFiddle:

  1. Open JSFiddle and create a new blank project by clicking the JSFiddle logo in the upper left.

  2. Type the code from the preceding listing into the JavaScript pane.

  3. Click the Run link in the top menu.

    A JavaScript prompt appears, asking you to enter your favorite day of the week.

  4. Enter a day of the week and click OK.

    The switch statement runs. You should see a result based on the value that you entered, as shown here.

    Determining a response by evaluating different cases.

    Determining a response by evaluating different cases.