DEV Community

Discussion on: Switch statements in javascript – How to refactor?

Collapse
 
lexlohr profile image
Alex Lohr

Switch statements can shine if multiple comparators should yield the same result. Otherwise objects, Maps (if the comparators are not strings) or if/else/ternary chains are better.

Collapse
 
ajayv1 profile image
Ajay Kumar Verma

Alex, didn't get the point.

You mean if comparators are string then switch would be better? I don't think so, as matching the string the object key will take same amount of time same as switch.

Collapse
 
lexlohr profile image
Alex Lohr

Maybe an oversimplified example may help:

const positionInWeek = (dayOfWeek) => {
  switch (dayOfWeek) {
    case "Monday":
    case "Tuesday":
      return "Start of the week"
    case "Wednesday":
    case "Thursday":
    case "Friday":
      return "Middle of the week"
    case "Saturday":
    case "Sunday":
      return "End of the week"
    default:
      throw new Error("Not a week day")
  }
}
Enter fullscreen mode Exit fullscreen mode

This would be harder to understand in an object or if-else-if-chain.