Vanilla JavaScript Switch statement

β€” 4 minute read

permalink

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 permalink

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 permalink

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 permalink

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! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter