Today I want to walk through the switch statement, of-course everyone knows the basic if...else statements and if you have been around for a while you learned those can get really out of hand.
Personally, I find myself using switch in various programming languages quite often.
JavaScript Switch elements
Here we see a basic switch statement:
let emoji = '๐ฅ';
switch (emoji) {
case '๐ค':
console.log('rock on');
break;
case '๐ฅ':
console.log('on fire!');
break;
default:
console.log('fake news');
}
// on fire!
As we can see we have case, break and default in the switch statement.
The switch statement will run through cases until it hits one that it equals that will return a break. The break will end the switch statement.
If no case is met, it will return the default statement if it's defined.
JavaScript Switch multiple cases
We can even do multiple cases with a switch statement. This looks like the following example:
let job = '๐';
switch (job) {
case '๐ค':
case '๐ธ':
case '๐จโ๐ค':
console.log('You must be a rock artist');
break;
case '๐ฅ':
case '๐จ':
case '๐':
console.log('You must be a firefighter');
break;
default:
console.log('No job?');
}
// You must be a firefighter
JavaScript Switch ranging case
Another cool thing we can do with for instance integers is seeing where they range. Let's see that in action.
let rickAndMortyIMDBScore = 92;
switch (true) {
case rickAndMortyIMDBScore >= 90:
console.log('Best show ever!');
break;
case rickAndMortyIMDBScore >= 80:
console.log('Pretty good');
break;
case rickAndMortyIMDBScore >= 70:
console.log('Mehh');
break;
default:
console.log('Not even worth it');
}
// Best show ever!
As you can see switch statement gets very useful.
Feel free to play with this Codepen:
See the Pen rNVgRJp by Chris Bongers (@rebelchris) on CodePen.
Thank you for reading, and let's connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter