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 ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API