An Idiosyncratic Blog

🧱 Ditch the long if, use array.includes

Published on
2 minutes read

Consider this very simple JavaScript code which we potentially write or read every day.

if (name === 'Optimus Prime' || name === 'Ratchet') {
  AutobotsRollOut()
}

Now, what if we wanted to check for more names?

if (name === 'Optimus Prime' || name === 'Ratchet' || name === 'BumbleBee' || name === 'IronHide') {
  AutobotsRollOut()
}

Nothing is wrong with this code, but it is a bit long. Let's make it shorter and clear.

const Autobots = ['Optimus Prime', 'Ratchet', 'BumbleBee', 'IronHide']
if (Autobots.includes(name)) {
  AutobotsRollOut()
}

We can use the includes() method on the array to check if the name is in the array. If we wanted to add more names, we could just add them to the array.

Alternate with Switch

We can use a switch statement to check for multiple values. Considering the above example, with a switch statement, we could write the code like this:

switch (name) {
  case 'Optimus Prime':
  case 'Ratchet':
  case 'BumbleBee':
  case 'IronHide':
    AutobotsRollOut()
    break
  default:
    break
}

I don't prefer switch statements, because it is a bit long and takes time to read. Also, prone to bugs if we add more cases and there is no break statement.

BUT WHAT ABOUT PERFORMANCE? For string comparisons, I'll take code clarity over speed. If this was in performance critical code, or it were in a library, sticking with the longer if statement would be a better choice.