Fallen Asleep
Fallen Asleep

Reputation: 21

Using Array.includes() instead of OR chain

Which is better? I'm concerned about both style/readability and performance.

someMathematicalExpression === 0 || someMathematicalExpression === 1 ||
 someMathematicalExpression === -1 || someMathematicalExpression === 11 || ...

vs.

[0,1,-1,11,...].includes(someMathematicalExpression)

The OR chain has the advantage of being more literal, whereas it might not be obvious from first glance what the intent of the .includes is.

On the other hand, the .includes can be much shorter, and it separates the solutions from the expression, making it easier to see which values will evaluate to true.
Most significantly, when someMathematicalExpression is fairly complex, the entire OR chain can become very operator-heavy, making it hard to read.

I just wanted to make sure I wasn't missing anything, or check to see if there was a third option I hadn't considered.

TL;DR: is there a reason to not use Array.Includes instead of an OR chain containing only === statements

Upvotes: 1

Views: 1169

Answers (1)

Bergi
Bergi

Reputation: 664444

The third option would be

const value = someMathematicalExpression;
value === 0 || value === 1 || value === -1 || value === 11 || ...

which importantly evaluates someMathematicalExpression only once. It might also be faster than the includes because it can use short circuiting and doesn't need to evaluate the whole array of solutions, but a compiler might be able to optimise that away so it shouldn't matter unless this is a performance bottleneck where you need to benchmark anyway. (In which case you might also want to consider trying a static Set and a has check)

So keep your code DRY by not repeating the mathematical expression, whether you find the array + includes approach or the comparison chain more readable is left to your personal judgement. Of course, includes also has the drawback that it requires an ES6+ environment, that might matter for you or not.

Upvotes: 1

Related Questions