The Switch Statement

Open the project folder

In our starter files, open the index.html page from this lessons folder:

06.Loops-and-conditionals > 06.The-switch-statement

What is a switch statement?

A switch statement is a way to provide as many outcomes as we want, based on a condition. We can also provide multiple outcomes with if and if...else statements, but as we discovered we need to add a condition to check against for each one.

Example

With a switch however, we just test against the same condition, such as here with our favourite pizza variable:

let favPizza = "Margherita";

switch (favPizza) {

}

The switch statement above looks similar in it's syntax to things like empty if statements and for loops. We pass in what we want to check against, such as our favPizza variable. Then inside we then set up different cases to handle what happens when there is a match:

let favPizza = "Margherita";

switch (favPizza) {
  case "Pepperoni":
    console.log("no pepperoni for me…");
    break;
  case "Vegetarian":
    console.log("no thanks…");
    break;
  case "Margherita":
    console.log("oh yeah!!");
    break;
  default:
    console.log("my fav cannot be found…");
}

Here we have three separate cases to handle what to do for each value, and we can have as many cases as we want.

Let’s look at the first one. We check if the favPizza is equal to “Pepperoni”. If it is, we run some code such as our console log. We then provide the break keyword to break out of the switch statement once we have a match. This will stop all the rest of the checks below from running.

This will keep running until a match is found. If there is no match we can also add a default clause too. And this will always run if there are no other matches.

Try it out

Over to the project file and let’s give this a go. Again, we have a user object:

let user = { name: 'Chris', role: 'editor' };

And we can set up a switch statement to check the user’s role. This will decide if the user can edit something on our site. For this, we can store it in a variable called canEdit:

let user = { name: 'Chris', role: 'editor' };
// default value of false
let canEdit = false;

Then our switch statement will check the user, and set the canEdit variable to be true if they have an editor or admin role:

switch (user.role) {
  case 'user':
    canEdit = false;
    break;
  case 'subscriber':
    canEdit = false;
    break;
  case 'editor':
    canEdit = true;
    break;
  case 'admin':
    canEdit = true;
    break;
  default:
    console.log('User role can not be found');
    canEdit = false;
}

Try this out with different roles, and an unrecognozed value to see the default case.

You may have already spotted a potential issue. This switch statement condition is user.role, but what if the user is null? This may be the case if the user is signed out. Try this out by updating the user:

let user = null;

You will see an error in the console:

Uncaught TypeError: Cannot read properties of null (reading 'role')

As expected, an error occurs since the role property no longer exists. One way to fix this is to use optional chaining:

switch (user?.role) {

This involves using a ? before checking the role property. This will avoid throwing errors when the property does not exist, and will run the default case. But more on this soon. Remember to also handle what to do if the value is null if required.

Merging cases

If there are two or more cases that all match, the first matching case will be used. And if we have multiple cases which run the same code, we can shorten it.

Here, the user and subscriber case run the same code. As does the last two cases.

We can merge our code as follows:

switch (user?.role) {
  case "user":
  case "subscriber":
    canEdit = false;
    console.log("user or subscriber");
    break;
  case "editor":
  case "admin":
    canEdit = true;
    console.log("editor or admin");
    break;
  default:
    console.log("User role can not be found");
    canEdit = false;
}

This includes some additional console log's to help with testing.

If we were to forget a break, the following cases would also run until a break keyword is finally found. So, it is important to not forget these inside each case.