TOC

The community is working on translating this tutorial into Italian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Control structures:

The switch statement

The switch statement is like a series of if statements, all checking the same variable, but with a different action for each possible value. It might sound complicated, but it's really not. Just have a look at this simple example:

let answer = prompt("Do you like JavaScript?");
switch(answer)
{
	case "yes":
		alert("That's great!");
		break;
	case "no":
		alert("Sorry to hear that!");
		break;
	case "maybe":
		alert("I'll ask again later...");
		break;	
}

In the first line, we ask a question. Then we use the answer variable as the condition for the switch statement. Inside the switch statement, we define multiple possible values to check against the answer variable (yes, no or maybe), using the case keyword. Each action will result in a different alert.

The break keyword

Notice the break keyword used at the end of each case. A switch statement requires that you properly exit each case, either by using the break keyword, or in case you are within a function, by using the return keyword to completely exit the function. If you omit this, execution will fall through to all cases below the one matching the value. You can test this easily by removing the break keywords from the example above and running the example again.

You may omit the last break keyword, since the switch statement ends there no matter what, but this is not true for all programming languages, so for consistency, many programmers tend to always include it for all cases.

Case groups

Sometimes you want several cases to perform the same action. No problem, because you can simply stack as many case statements on top of each other, to allow them to use the same code. Here's an example:

let answer = prompt("Do you like JavaScript?");
switch(answer)
{
	case "yes":
		alert("That's great!");
		break;
	case "no":
	case "nope":	
	case "nay":
	case "nix":
		alert("Sorry to hear that!");
		break;
	case "maybe":
		alert("I'll ask again later...");
		break;	
}

As you can see, we now have a whole list of options for the "no" part of the switch statement, with different variations of this negative response all resulting in the same message.

The default keyword

The above example has a pretty obvious flaw: If the user doesn't enter the exact value to match one of the cases, nothing will happen. For a situation like this, it's nice to have a fallback action - something that will be executed if none of the other options are relevant. Fortunately for us, JavaScript allows us to do just that, using the default keyword. Here's a modified version of the above example where we add this:

let answer = prompt("Do you like JavaScript?");
switch(answer)
{
	case "yes":
		alert("That's great!");
		break;
	case "no":
		alert("Sorry to hear that!");
		break;
	case "maybe":
		alert("I'll ask again later...");
		break;
	default:
		alert("Please enter 'yes', 'no' or 'maybe'...");
		break;
}

With this in place, our switch statement can handle all situations, because we have a fallback action from the default keyword.

Case comparison

Another thing we would need to consider, if the above example was used in a real world scenario, is how each case is compared to the condition. For instance, we check for "yes", but strings are always compared case-sensitive, so if the user wrote "Yes", "YeS" or "YES" instead, our first case would not match. We always need to handle this, for instance by converting the answer to lowercase before checking it:

let answer = prompt("Do you like JavaScript?");
switch(answer.toLowerCase())
{
	case "yes":
		alert("That's great!");
		break;
...

Another thing you need to consider is the fact that all comparison is done using the strict equality comparison operator (===). This means that if your expression in the switch statement is a string, you can only compare it to another string, even if you know that this string is in fact a number.

Allow me to illustrate with an example:

let answer = prompt("41 or 42?");
switch(answer)
{
	case 41:
		alert("41? Really??");
		break;
	case 42:
		alert("42 - of course!");
		break;
	default:
		alert("Unknown answer...");
		break;
}

This example will NOT work as expected. Why? Because the result of the prompt() is a text string (even if the user enters a numerical value), but we compare it to numbers (41 or 42). You will need to handle this, for instance by turning the answer into a number before checking it, or by comparing it to strings instead. Let's change the first line of the example and use the Number() function to turn the result of the prompt() function into a number:

let answer = Number(prompt("41 or 42?"));
switch(answer)
{
	case 41:
		alert("41? Really??");
		break;
	case 42:
		alert("42 - of course!");
		break;
	default:
		alert("Unknown answer...");
		break;
}

Summary

With the switch statement, you can compare an expression to multiple choices and perform an action based on it, kind of like a series of if..else..if statements, but in a more readable format. Remember that the switch statement uses strict equality comparison.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!