Convert string comparison chain to array.includes
Replace || value === 'aString'
and && value !== 'aString'
chains with array.includes()
.

This refactoring replaces string comparison chains with an array.includes()
call. It works for regular string comparisons with || ===
and for negated string comparisons with && !==
. When the string comparison is negated, the .includes
call is prefixed with !
.
Example
if (obj.property === "value1"
|| obj.property === "value2"
|| obj.property === "value3") {
// ...
}
becomes
if (["value1", "value2", "value3"].includes(obj.property)) {
// ...
}
Why is this refactoring helpful?
Converting a sequence of string comparisons into an array.includes
call makes it easy to add or remove elements and enables extracting the string array into a variable.
What do I need to consider?
The compared expression is only evaluated once
For example, consider refactoring
f() === "a" || f() === "b"
into
["a", "b"].includes(f())
Before the refactoring, f
is called one or two times. After the refactoring (with .includes()
) f
is only called once.
If f
has a side effect, this side effect would have been called a different number of times, potentially changing the behavior. This behavior applies not just to function and methods calls but also to getters that can potentially have side effects.