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 blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

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

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay