JavaScript: Switch Statements

If you've started coding almost any JavaScript using the information in previous tutorials - it's pretty likely that you've ran into a case where you end up stacking a lot of 'if' statements to compare a variable to various values - something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
var uInput = prompt('Enter a value');
if(uInput=='Hi')
{
	alert('Hello!');
}
else if(uInput == 'Bye')
{
	alert('Goodbye!');
}
else if(uInput=='How you doing?')
{
	alert('I\'m good thanks!');
}

Isn't it annoying how you have to specify the variable to compare and the == comparison operator over and over again? Well this is where 'switch' statements become very useful!

Switch statements are pretty much just an easy way to compare one variable to a variety of values. You begin a switch statement by firstly using the switch keyword, and then specifying the variable you want to evaluate in some regular brackets. You then specify the different cases (comparisons) inside curly brackets - we'll learn how to formulate these in a second. So you should be imagining something that looks a bit like this:

1
2
3
4
5
6
var uInput = prompt('Enter a value');

switch(uInput)
{
	//Different cases go here
}

So let's learn how to create cases! We can specify a case inside the curly brackets by writing the keyword case followed by the value we want to compare (to 'uInput' in this case), followed by a colon. We then put any code we want executed when this case is met, and then end the case with the 'break' keyword followed by a semicolon. For example:

1
2
3
4
5
6
7
8
var uInput = prompt('Enter a value');

switch(uInput)
{
	case 'Hi':
		//Some code goes here
		break;
}

So let's just go ahead and build in all the functionality that the small code snippet at the beginning of this tutorial had by simply adding some more cases to our 'switch' statement:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var uInput = prompt('Enter a value');

switch(uInput)
{
	case 'Hi':
		alert('Hello!');
		break;
	case 'Bye':
		alert('Goodbye!');
		break;
	case 'How you doing?':
		alert('I\'m good thanks!');
		break;
}

On running this, we should see that everything seems exactly the same as the code at the beginning of this tutorial, but our code is a lot cleaner, easier, and generally, in my opinion, better! But how do you accomplish 'else' type statements using switch statements? Luckily, with extreme ease!

If we wanted to add an 'else' case to our switch statement, we simply have to add a case called default (we don't even have to write the case keyword) - this will execute if none of the other cases are met.