To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the use of functional cookies. For more information read this page.

Switch statements in JavaScript

Switch statements are often known as case statements. These are a conditional statement that can have multiple cases (hence the name case statement). It works very similarly to an if statement with many else if statements within it.

Switch statements in JavaScript

Switch statements are an important part of any JavaScript program since they reduce the amount of unnecessary code (which with web languages is very important).

JavaScript
//Simple if statement with elseif
var test1 = 5;
if(test1 == 0) {
	alert ("There's nothing");
}
else if(test1 == 1) {
	alert ("It is now 1");
}
else {
	alert ("It's not one or zero");
}
		

But this is less efficient than a switch statement. A switch statement for the same code would look like:

JavaScript
//Simple switch statement for comparison to if statement
var test1 = 5;
switch (test1)
{
	case 0:
		alert ("There's nothing");
		break;
	case 1:
		alert ("It is now 1");
		break;
	default:
		alert ("It is not one or zero");
}
Provide feedback on this page
Comments are sent via email to me.