DEV Community


Posted on

Switch Statements in JavaScript

Today I'll be doing a quick tutorial on how to use a switch statement in JavaScript and when it's appropriate to use. I bring this up because I found my self in a situation where I was writing a series of if statements that a switch made for a much better solution.

When to use a switch statement?

Switch statements are perfect for when different outputs may require a different following reaction. For example x + y can have many different outcomes but what if you need a different reaction depending on what the output turns out to be? You could write a series of if statements or you can contain the logic entirely within a switch statement.

How to use it:

The switch itself will take in an expression and depending on what case the expression fulfills will be the code block that performs.

switch(expression) {
  case 1:
    // Does something
  case 2:
    // Does something else
    // If none are met this one performs
Enter fullscreen mode Exit fullscreen mode

That's the basic structure of how it will look. Notice how at the end of each case we break out of the code. If you don't it will keep running through the cases.

Here's a full on example of it in use. It will be a function that takes in a species as a string and return a name of a famous member of said species.

const famousMemberOfSpecies = (species) => {
    let famousMember;

        case "Wookie":
            famousMember = "Chewbacca";
        case "Twi'lek":
            famousMember = "Hera Syndulla";
        case "Weequay":
            famousMember = "Hondo Ohnaka";
        case "Hutt":
            famousMember = "Jabba";
            return "No famous members found";

    return famousMember;

console.log(famousMemberOfSpecies("Hutt"));//Should log "Jabba" to the console.

console.log(famousMemberOfSpecies("Nexu"))//Should log "No famous members found" to the console.
Enter fullscreen mode Exit fullscreen mode

Notice how I used the default case to handle an output that might not need a response.

You can get much more complicated with these and perform entire code blocks in each case but the point is you can handle different outputs with different responses using this and avoid overusing if/else statements that are more appropriate for more complicated conditional statements.

Anyways that'll be it for today. Happy Coding!

Top comments (0)