Understanding Switch Cases in JavaScript

Paul Halliday

We recently looked at if statements, but now it’s time to switch things up! We’d look to use the switch statement whenever we have multiple test cases for a particular expression. If you find yourself writing multiple if/else statements, this may be worth condensing into a switch statement.

As a result, in many ways, the switch statement is similar to the if statement:

  1. The switch statement firstly evaluates an expression.
  2. Using case syntax, it compares the result of the expression with the particular case.
  3. It then executes any code inside of the case until the break keyword is found. If the break keyword is not added to the case, it’ll continue to execute further code within the block.
  4. Alternatively, if there are no matching cases, an optionaldefault case can be added to execute a block of code regardless.
Learn JavaScript basics for free

Let’s look at a version of this in code:

const sky = "blue";

switch (sky) {
  case "red":
    console.log("Uh oh.");
    break;
  case "blue":
    console.log("A good day for golf!");
    break;
  default:
    console.log("Try looking up for a hint.");
}

As the value of sky is equal to blue, the case blue is executed. However, if we changed the value of sky to an empty string "" we’d get the default case.

Here’s the same example, with a little twist:

const sky = "blue";

switch (sky) {
  case "red":
  case "purple":
  case "yellow":
  case "green":
    console.log("Uh oh.");
    break;
  case "blue":
    console.log("A good day for golf!");
    break;
  default:
    console.log("Try looking up for a hint.");
}

As you can see in this second example, it’s perfectly valid to have multiple case statements that share the same block of executed code.

Summary

You should now have the hang of switch statements within JavaScript. Use this new power wisely - don’t turn every if statement into a switch, only those that are getting too long to read tersely. And don’t forget to break out of the switch statement once you’ve found the right condition, otherwise the rest of the code will run and have an impact on your code’s performance. default doesn’t need a break statement, because if your code reaches that point, it has already gone through the whole code of the switch case anyway.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#