简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM