Programming & Scripting Tutorials

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 (no pun intended, you might get the 'joke' once you've finished following this tutorial) where you end up stacking a lot of if statements to compare a variable to various values – something like this:

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 useful!

Switch statements are basically just an easy way to compare one variable to a variety of values. You begin a switch statement by first 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:

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 these 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:

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:

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 better!
But how do you accomplish 'else' type statements using switch statements?
Well, it's very easy!
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.


This Javascript tutorial was written by


Back to Javascript

Advertisement: