March 5th, 2020
Today we’ll be talking about an alternative to the traditional if-else statements, and it’s called switch case! If you haven’t seen Day 3, please click on the link below!
Javascript in 15 Days : Conditionals
So, let’s jump straight in, shall we?
Here’s an example of using switch-case to toggle a light switch:
var toggle = 0;
switch (toggle) {
case 0:
console.log('Light has been turned off!'); // this is most likely to show
break;
case 1:
console.log('Light has just been turned on');
break;
default:
console.log('Please re-check your value');
}
So, we can see that we first initialize the value of a variable, (here’s it’s “toggle”) and we use a switch-case to check whether it has a value of 0, 1 or something else, and we log the output based on this. The following example can also be written in if-else statements as below:
var toggle = 0;
if (toggle === 0) {
console.log('Light has been turned off!'); // this is more likely to show
} else if (toggle === 1) {
console.log('Light has just been turned on!');
} else {
console.log('Please re-check your value!');
}
As you can see, it’s so much simpler with switch case! So, you might be wondering, when to use a switch-case? Well, a couple of examples would be when you’re checking what day of the week it is, or a simple true or false statement, or even when intending to do different things based on the month of the year! As you can see, switch-case is definitely useful! So, here’s the end of today’s session! Hope you enjoyed and learned new things today! We will be having a review day tomorrow! See you soon!