Chapter 15

Doing Different Things with Switch

Switch statements 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.

In this chapter, we use a switch statement to write a calendar program that gives you suggestions for things to do, based on what day of the week it is.

image

Writing a Switch

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.

Let’s take a look at ...

Get JavaScript For Kids For Dummies now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.