Subscribe

Vanilla JavaScript Switch statement

✍️

Learn all about the amazing Vanilla JavaScript Switch statement

5 Apr, 2020 Β· 3 min read

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next πŸ“–

Removing all vowels with JavaScript

3 Dec, 2022 Β· 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 Β· 3 min read

10 games to learn JavaScript

Join 2097 devs and subscribe to my newsletter