switch

A switch statement allows us to evaluate an expression and then compare the value to some other values called 'cases'. Switch statements are used heavily in a package called 'Redux', which allows us to manage the state of an application. We'll talk more about that later. A switch is a type of conditional, but it allows us to check for a bunch of different cases in a super efficient way.

Sample Code

To learn switch statements it's best to look at the syntax and write your own. Start by adding the following code:

var friend = "";

switch (friend) {
  case "Fred":
    console.log("Hey Fred, let's go golfing.");
    break;
  case "Karl":
    console.log("Let's hang.");
    break;
  case "John":
    console.log("Sorry, I'm busy right now.");
    break;
  default:
    console.log("Hey " + friend + "can I call you back in a minute.");
}

Copy the code above and play with changing the value of the friend variable. For instance, change it to var friend = "Fred".

Couple things to ponder: What happens when you change it to var friend = Jenn? What is the default keyword doing?

Practice

Pick one or both:

1- It's cliche, but it's good to know how to do it: Write a switch that says what we should wear based on a changing weather variable. Deal with 0 or lower, 0-32, 32-50, etc. For instance, if it is 75, we might get a console statement that says: "It's 75 degrees out. You could probably get away with shorts today."

2- Write a switch that would diagnose common issues with a car. So, have a variable called problem that is a string. Create a bunch of cases that would print how to fix the problem to the console. Come up with about 5 different cases and don't forget a default.

Last updated