DEV Community

Analogy | Absence | Example
Analogy | Absence | Example

Posted on • Updated on

The Right Way and the Wrong Way to use Switch Statements

Once I learned how to write switch statement, I never wanted to go back to if/else statements because switch statements are so much cleaner looking and easier to read. But I have learned that even if a switch statement works correctly, that doesn't mean you've used it correctly. My mistake was using true as the expression to be evaluated. Even though it works, this is considered bad practice.

The Mozilla Developer Network Web Docs states the following:

A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression...

The Wrong Way to use a switch statement

let myVar = "Saturday";

myFunction = () => {
  switch (true) {
    case myVar === "Tuesday":
      console.log("weekday");
    case myVar === "Saturday":
      console.log("weekend");
    default:
      return null;
  }
};

myFunction();
// "weekend"
Enter fullscreen mode Exit fullscreen mode

The Right Way to use a switch statement

 let myVar = "Saturday";

myFunction = () => {
  switch (myVar) {
    case "Tuesday":
      console.log("weekday");
    case "Saturday":
      console.log("weekend");
    default:
      return null;
  }
};

myFunction();
// "weekend"
Enter fullscreen mode Exit fullscreen mode

Controversy

That said, some people like using the switch (true) pattern because it can make code blocks easier to read compared to long, complex if/else statements. This whole issue is quite controversial. My advice is to only use the switch (true) pattern under the following circumstances:

  1. The readability of the code is significantly improved when using switch (true)
  2. Your team is ok with using this pattern

Another Wrong Usage of a Switch statement: Comparing Values

While we're on the subject, you can't use the switch statement if you are comparing values. As said above, switch is for evaluating the input expression and then testing to find the first case expression whose evaluation matches the input expression. For example, this won't work:

The Wrong Way to compare values

let myVar = 5;

myFunction = () => {
  switch (myVar) {
    case myVar > 10:
      console.log(`greater than ten`);
    case myVar < 10:
      console.log(`less than ten`);
    default:
      return null;
  }
};

myFunction();
Enter fullscreen mode Exit fullscreen mode

The Right Way to compare values

let myVar = 5;

myFunction = () => {
  if (myVar > 10) {
    console.log(`greater than ten`);
  } else if (myVar < 10) {
    console.log(`less than ten`);
  }
};

myFunction();
// less than ten
Enter fullscreen mode Exit fullscreen mode

The moral of the story is:

  • Use a switch statement if you want to test the value of a variable
  • Use an if/else statement if you want to compare the value of a variable

Top comments (0)