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