Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 4.4Switch statements in JavaScript

Part 4.4Switch 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");
}
Feedback 👍
Comments are sent via email to me.