JavaScript 101-#16 – Switch statement

I hope that you understood and enjoyed the loops we discussed previously. The next topic in JavaScript 101 series, after loops, we will explore is “switch” statement. Curriculum for today will be all about what it is, how does it work and why it is better to use is in some cases rather than “if” statement

“Switch” statement works in similar way like “if”, but it has less complex syntax. Well, in case you have to code some advanced code. If your goal is to create simple script checking for two states, nothing can beat “if” statement. However, imagine following situation … You need to know what programming language user wants to learn and also provide some reaction (message) according to his or her answer. There will be six languages to choose from. These languages will be – JavaScript, Python, Ruby, PHP, C++ and Java. If you would decide to solve this with “if” statement, you would need couple of “if else” block for every possible answer. We will also include a “default” answer for unknown choice.

JavaScript:

// solution via “if” statement
var choice = prompt(“What language do you want to learn (JavaScript, Python, Ruby, PHP, C++ or Java)?”);
if (choice === “JavaScript”) {
 console.log(“Ever heard about Brendan Eich?”);
} else if (choice === “Python”) {
 console.log(“Seems like Guido van Rosum will be your next hero.”);
} else if (choice === “Ruby”) {
 console.log(“You have to learn more about Yukihiro Matsumoto!”);
} else if (choice === “PHP”) {
 console.log(“Another one for Rasmus Lerdorf?”);
} else if (choice === “C++”) {
 console.log(“What do you think about Bjarne Stroustrup?”);
} else if (choice === “Java”) {
 console.log(“Read more about James Gosling.”);
} else {
 console.log(“Please choose only from languages in parenthesis.”);
}

As you can see, this way is not much a solution, but rather torture. Writing the condition all over again for every single case could easily make someone nuts. For situations like this, we can use “switch” statement instead. Switch comprises of two parts – expression and block of code inside curly brackets. Expression can be either some variable or method like prompt(), confirm(), etc. The syntax doesn’t end here. Another important thing is inside curly brackets. In brackets you have to define “case” for every choice. Case is created by writing “case” keyword followed by choice (strings are in quotes) and colons. On the next line is code to be executed. The last line of EVERY case has to be “break;”. This will cause the “switch” to stop when it finds the right case for provided answer. Without this, “switch” would continue and execute all next cases. The last thing that has to be included is “default” case. It works like “else” in “if” – when none of the cases suits the choice. This case is created by writing “default” keyword followed by colons. On the next line is code to be executed and again line with “break” command. You can have as many cases you want.

JavaScript:

// syntax of “switch” statement
switch ( expression ) {
 case …. :
   code to be executed;
   break;
 case …. :
   code to be executed;
   break;
 default:
   code to be executed;
   break;
}

In order to help you understand “switch” better, let’s convert our previous test dummy (example with languages) to switch statement. Unlike “if” statement “switch” will use only name of variable as an expression. There is no need to comparison because it will be handled by individual cases.

JavaScript:

// solution via “switch” statement
var choice = prompt(“What language do you want to learn (JavaScript, Python, Ruby, PHP, C++ or Java)?”);

// creating “switch” statement with choice as expression
switch (choice) {
 case “JavaScript”:
   console.log(“Ever heard about Brendan Eich?”);
   break;
 case ”Python”:
   console.log(”Seems like Guido van Rosum will be your next hero.”);
   break;
 case ”Ruby”:
   console.log(”You have to learn more about Yukihiro Matsumoto!”);
   break;
 case ”PHP”:
   console.log(”Another one for Rasmus Lerdorf?”);
   break;
 case ”C++”:
   console.log(”What do you think about Bjarne Stroustrup?”);
   break;
 case ”Java”:
   console.log(”Read more about James Gosling.”);
   break;
 // when no case suits user's choice
 default:
   console.log(”Please choose only from languages in parenthesis.”);
   break;
}

This way it is much faster to solve our problem without re-typing the condition (expression in case of “switch”) every time. As I mentioned, you can make the code a bit shorter by removing the variable and using the prompt method as an expression. The rest of code will remain the same.

JavaScript:

// without variable
switch (prompt("What language do you want to learn (JavaScript, Python, Ruby, PHP, C++ or Java)?")) {
 case “JavaScript”:
   console.log(“Ever heard about Brendan Eich?”);
   break;
 … 
}

I hope that seeing “switch” in action helped you understand the concept of it. Let’s do another example for movie fans. We are going to ask user which movie director from available names do they like more and then suggest some movies according to their choice. Available choices will be – Stephen Spielberg, Christopher Nolan, Martin Scorsese, Francis Ford Coppola, Quentin Tarantino and Alfred Hitchcock. To make it shorter, we will put the prompt() method right inside the expression of “switch”.

JavaScript:

switch (prompt(“Which movie director do you like more (Stephen Spielberg, Christopher Nolan, Martin Scorsese, Francis Ford Coppola, Quentin Tarantino, Alfred Hitchcock)?”)) {
 case “Stephen Spielberg”:
   console.log(“Watch Jurassic Park, Indiana Jones or Jaws.”);
   break;
 case ”Christopher Nolan”:
   console.log(”Watch Dark Knight, Interstellar or Inception.”);
   break;
 case ”Martin Scorsese”:
   console.log(”Watch GoodFellas, The Wolf of Wall Street or Shutter Island.”);
   break;
 case ”Francis Ford Coppola”:
   console.log(”Watch The Godfather, Tetro or Tucker: The Man and His Dream.”);
   break;
 case ”Quentin Tarantino”:
   console.log(”Watch Pulp Fiction, Kill Bill or Django Unchained.”);
   break;
 case ”Alfred Hitchcock”:
   console.log(”Watch Psycho, The Birds or Vertigo.”);
   break;
 default:
   console.log(”Please choose only from available names.”);
   break;
}

Another example can be script for simple fitness app. User will tell what is his favorite sport activity and the script will suggest a challenge he should do. For choices let’s use squats, push-ups, pull-ups, chin-ups, dips and crunches.

JavaScript:

switch (prompt(“Which one is favorite sport activity - squat, push-up, pull-up, chin-up, dip, crunches?”)) {
 case “squat”:
   console.log(“Do 25 squats, 5 rounds.”);
   break;
 case “push-up”:
   console.log(“Do 15 push-ups, 4rounds.“);
   break;
 case “pull-up”:
   console.log(“Do 12 pull-ups, 4rounds.”);
   break;
 case “chin-up”:
   console.log(“Do 18 chin-ups, 4 rounds.”);
   break;
 case “dip”:
   console.log(“Do 12 dips, 4 rounds.”);
   break;
 case “crunches”:
   console.log(“Do 30 crunches, 4 rounds.”);
   break;
 default:
   console.log(“I have no challenge for this activity.”);
   break;
}

To end it on lighter note, let’s create simple “switch” with two cases. Do you like more cats or dogs?

JavaScript:

switch (prompt(“Do you like cats or dogs?”)) {
 case “cats”:
   console.log(“Are you freedom loving individualist?“);
   break;
 case “dogs”:
   console.log(“Do you like people around yourself?”);
   break;
 default:
   console.log(“C'mon, dogs or cats?”);
   break;
}

Summary

This all for today ladies and gentlemen. I hope you enjoyed today’s tutorial on “switch” statement and learned something new. In case you want to help with understanding any part, please leave a comment or write me a message via links below. Thanks.

If you liked this article, please subscribe so you don't miss any future post.

If you'd like to support me and this blog, you can become a patron, or you can buy me a coffee 🙂

By Alex Devero

I'm Founder/CEO of DEVERO Corporation. Entrepreneur, designer, developer. My mission and MTP is to accelerate the development of humankind through technology.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.