I’m trying to improve an old React web application for work when i stumble upon this variable:
const condition = (
param !== const1 && param !== const2 && param !== const3 && ...
)
Is there a best practise to improve this very long and condition?
3
Answers
You can shorten with the array method
includes
.This will return true if the array has the variable
param
, then use ! to switch the boolean to false:Depending on your situation using condition with the ! operator (
!condition
) and declaring without might improve readability:The declaration above will likelly be my prefered option. However, there are a lot of other ways to achieve this:
In the line below
indexOf
will return -1 when param is not part of the array:In the line below array method
every
tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value:Create an array for your conditions.
You can also use some
The idiomatic way of performing such check if you’re checking running the
!==
comparison for all items you should use theArray.every
functional predicate.It checks that every item matches the condition: