Switch Statements in JavaScript

by kirupa   |   6 January 2013

In a world filled with beautiful if, else, and else if statements, the need for yet another way of dealing with conditionals may seem unnecessary. People with longer beards than you and me disagreed, so we have what are known as switch statements. In this short tutorial, I will describe how to use switch statements and why, putting my initial snarkastic comments aside, they can provide some value.

Let's get started!

Using a Switch Statement

The basic structure of a switch statement is as follows:

switch(expression) {
	case value1:
		statement;
		break;
	case value2:
		statement;
		break;
	case value3:
		statement;
		break;
	default:
		statement;
		break;
}

The thing to never forget is that a switch statement is nothing more than a conditional statement that tests whether something is true or false. That something is a variation of whether the result of evaluating the expression equals a case value. Now, I do realize that this probably makes no sense if you have never worked with switch statements before. Let's make this explanation actually make sense by looking at a better example:

var color = "green";

switch(color) {
	case "yellow":
		alert("yellow color");
		break;
	case "red":
		alert("red color");
		break;
	case "blue":
		alert("blue color");
		break;
	case "green":
		alert("green color");
		break;
	case "black":
		alert("black color");
		break;
	default:
		alert("no known color specified");
		break;
}

In this simple example, I have a variable called color whose value is set to green:

var color = "green";

The color variable is also what I specify as my expression to my switch statement:

switch(color) {
	case "yellow":
		alert("yellow color");
		break;
	case "red":
		alert("red color");
		break;
	case "blue":
		alert("blue color");
		break;
	case "green":
		alert("green color");
		break;
	case "black":
		alert("black color");
		break;
	default:
		alert("no known color specified");
		break;
}

Our switch statement contains a collection of case blocks. Only one of these blocks will get hit with their code getting executed. The way this chosen one gets picked is by matching a block's case value with the result of evaluating the expression. In our case, because our expression's evaluates to a value of green, the code inside the case block whose case value is also green gets executed:

switch(color) {
	case "yellow":
		alert("yellow color");
		break;
	case "red":
		alert("red color");
		break;
	case "blue":
		alert("blue color");
		break;
	case "green":
		alert("green color");
		break;
	case "black":
		alert("black color");
		break;
	default:
		alert("no known color specified");
		break;
}

Note that only the code inside the green case block gets executed. That is thanks to the break keyword that ends that block. When your code hits the break, it exits the entire switch block and continues executing the code that lies below it. If you did not specify the break keyword, you will still execute the code inside the green case block. The difference is that you will then move to the next case block (the black one in our example) and execute any code that is there. Unless you hit another break keyword, your code will just move through every single case block until it reaches the end.

With all of this said, if you were to run this code, you will see an alert window that looks as follows:

green color alert

You can alter the value for the color variable to other valid values to see the other case blocks execute. Sometimes, no case block's value will match the result of evaluating an expression. In those cases, your switch statement will just do nothing. If you wish to specify a default behavior, add a default block:

switch(color) {
	case "yellow":
		alert("yellow color");
		break;
	case "red":
		alert("red color");
		break;
	case "blue":
		alert("blue color");
		break;
	case "green":
		alert("green color");
		break;
	case "black":
		alert("black color");
		break;
	default:
		alert("no known color specified");
		break;
}

 

Note that the default block looks a bit different than your other case statements. More specifically, it actually doesn't contain the word case.

Similarity to an If/Else Statement

At the beginning, I mentioned that a switch statement is used for evaluating conditions - just like an if / else statement. Given that this is a major accusation, let's explore this in further detail by first looking at how an if statement would look if it were to be literally translated into a switch statement.

Let's say we have an if statement that looks as follows:

var number = 20;

if (number > 10) {
	alert("yes");
} else {
	alert("nope");
}

Because the value of our number variable is 20, our if statement will evaluate to a true. Seems pretty straightforward. If that wasn't straightforward, I highly suggest you read the If and Else Statements in JavaScript tutorial first.

Now, let's turn this into a switch statement:

switch(number > 10) {
	case true:
		alert("yes");
		break;
	case false:
		alert("nope");
		break;
}

Notice that our expression is number > 10. The case value for the case blocks is set to true or false. Because number > 10 evaluates to true, the code inside the true case block gets executed. While your expression in this case wasn't as simple as reading a color value stored in a variable like in the previous section, our view of how switch statements work still hasn't changed. Your expressions can be as complex as you would like. If they evaluate to something that can be matched inside a case value, then everything is golden...like a fleece!

Now, let's look at a slightly more involved example. This time, let's convert our earlier switch statement involving colors into equivalent if / else statements. The switch statement we used earlier looks as follows:

var color = "green";

switch(color) {
	case "yellow":
		alert("yellow color");
		break;
	case "red":
		alert("red color");
		break;
	case "blue":
		alert("blue color");
		break;
	case "green":
		alert("green color");
		break;
	case "black":
		alert("black color");
		break;
	default:
		alert("no color specified");
		break;
}

This switch statement converted into a series of if / else statements would look as follows:

var color = "green";

if (color == "yellow") {
	alert("yellow color");
} else if (color == "red") {
	alert("red color");
} else if (color == "blue") {
	alert("blue color");
} else if (color == "green") {
	alert("green color");
} else if (color == "black") {
	alert("black color");
} else {
	alert("no color specified";
}

As you can see, if / else statements are very similar to switch statements and vice versa. The default case block becomes an else block. The relationship between the expression and the case value in a switch statement is combined into if / else conditions in an if / else statement.

Deciding Which to Use

In the previous section, you saw how interchangeable switch statements and if / else statements are. When you have two ways of doing something very similar, it is only natural to want to know when it is appropriate to use one over the other. In a nutshell, use whichever one you prefer. There are many arguments on the web about when to use switch vs an if / else, and the one thing is that they are all inconclusive.

My personal preference is to go with whatever is more readable. If you look at the comparisons earlier between switch and if / else statements, you'll notice that if you have a lot of conditions, your switch statement tends to look a bit cleaner. It is certainly less verbose and a bit more readable. What your cutoff mark is for deciding when to switch (ha!) between using a switch statement and an if / else statement is entirely up to you. I tend to draw the line at around four or five conditions.

Second, a switch statement works best when you are evaluating an expression and matching the result to a value. If you are doing something more complex involving weird conditions, type checking, etc., you probably want to use something different. That could involve something even more different than a if / else statement, by the way!

To reiterate, use whatever you like. For every person who agrees with what I've written, you'll find someone who convincingly can provide a counter argument.  If you are part of a team with coding guidelines, then follow them. Whatever you do, just be consistent. It makes your life as well as the life of anybody else who will be working in your code a little bit easier.

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly via e-mail, facebook, or twitter.

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!