Setting Variables Using Switch Statements In JavaScript

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"

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"

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"

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: geeksforgeeks.org/switch-vs-else

Happy coding!