2
\$\begingroup\$

Let's say I have this function called coolName that takes an argument name and decides whether it's a cool name:

function coolName(name) {
  const n = name.toLowerCase();
  return n === 'peter' || n === 'paul' || n === 'mary';
}

You could achieve the same using this approach:

function coolName(name) {
  return ['peter', 'paul', 'mary'].includes(name.toLowerCase());
}

For 3 or more values I need to compare to, I prefer the second approach.

Your thoughts?

\$\endgroup\$
  • 3
    \$\begingroup\$ If you expect many calls to occur, you could use a Set and call has. The set is slower to construct than an array, but has is much faster than includes on large collections. It also notifies the reader that the collection is not meant to have duplicates. Otherwise the second approach is canonical and readable. Even a very large list would maintain strong readability. \$\endgroup\$ – butt Jan 14 at 19:01
  • \$\begingroup\$ For such a simple case the only difference is down to a personal preference. Some people use yoda style with the first approach to improve its glanceability and break it into multiple lines ending on ||. Unless you see a difference in devtools profiler you shouldn't speculate on performance and change the code based on a guess or an idea what will run faster because the actual difference is likely to be within 0.001% of the task's total running time. \$\endgroup\$ – wOxxOm Jan 21 at 5:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.