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!

Top comments (0)