DEV Community

Cover image for Setting Variables Using Switch Statements In JavaScript
Kyle Schwartz
Kyle Schwartz

Posted on

Setting Variables Using Switch Statements In JavaScript

Here is a snippet showing an example of how this would be done. Each animal has a favorite color which we will determine using a switch statement.

const animal = "dog";

const color = (()=>{
    switch (animal) {
        case "cat":
            return "yellow"
        case "dog":
            return "blue"
        case "fish":
            return "green";
    }
})();

console.log(color); // "blue"
Enter fullscreen mode Exit fullscreen mode

And a similar example with parameter passing:

const color = (animal) => (()=>{
    switch (animal) {
        case "cat":
            return "yellow"
        case "dog":
            return "blue"
        case "fish":
            return "green";
    }
})();

console.log(color("fish")); // "green"
Enter fullscreen mode Exit fullscreen mode

And just to show how much cleaner the above version is, here is an example using an if/else statement:

const color = (animal) => {
  if (animal === "cat")
      return "yellow";
  else if (animal === "dog")
      return  "blue";
  else if (animal === "fish")
      return "green";
};

console.log(color("fish")); // "green"
Enter fullscreen mode Exit fullscreen mode

While, yes, the if/else version is technically shorter, you repeat yourself, it is less readable (subjectively), and it is inherently slower (at scale). With switch statements, the expression is only evaluated once, but with our if/else it is evaluated 3 times. Although, this example is short, so it may not affect performance. GeeksforGeeks has a great article comparing the two: https://www.geeksforgeeks.org/switch-vs-else/

Happy coding!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Image of PulumiUP 2025

From Cloud to Platforms: What Top Engineers Are Doing Differently

Hear insights from industry leaders about the current state and future of cloud and IaC, platform engineering, and security.

Save Your Spot

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️