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!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs