switch-conditional-statment-js

JavaScript Exercise 08: Switch Statement

In the last exercise, we’ve learn the if…else statement in JavaScript. Today, we are going to learn another conditional statement: the switch statement. The difference between if…else and switch statement is that switch is designed to handle more cases. Let’s take a look at the following example:

Exercise 8.1 Switch conditional statement in JavaScript

today = 2;

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

document.write(day);

In the code, today can be a number from 0 to 6, each represents a day in a weak. As you can see from the result, there is only one case is run, because there is a break in every cases, which means when that case is run, the whole switch statement is finished.

You may think that you can do the same thing with if…else statement, yes you can. but the whole program will be very redundant. Actually as an exercise, you should try to turn this program into if…else statement.

Exercise 8.2 Fall-through in switch statement

What if we want to do the same thing for several conditions? Check out the following code.

today = 2;

switch (today) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        day = "It's weekday";
        break;
    case 0:
    case 6:
        day = "It's weekend";
        break;
}

document.write(day);

Try to change the variable today to a different number between 0 to 6. It works exactly as we wanted.

Exercise 8.3 Default of switch in JavaScript

The last thing about switch statement is the default keyword. It is for all other cases, in other words, when there is no condition matches.

today = 3;

switch (today) {
    case 0:
    case 6:
        day = "It's weekend";
        break;
    default:
        day = "It's weekday";
        break;
}

document.write(day);

In this example, everything other than 0 and 6 will go to default. So you can try to give 10 to today, see what happens.

Exercise 8.4 Your turn

Here are two exercises for you:

  1. Turn the example above into month-based.
  2. Turn the previous example into season-based.

Exercise 8.5 Conclusion on conditional statements

That’s all for conditional statements. If…else and switch are commonly used among all programming language. Make sure you understand everything that we’ve discussed and feel free to ask if you got any question.