This rule raises an issue when .indexOf() or .lastIndexOf() are used with comparison operators to check element
existence, or when Array#some() is used for simple equality checks that could be replaced with .includes().
Using .indexOf() or .lastIndexOf() with comparison operators like !== -1 or >= 0 to check if
an element exists is less readable and semantic than using .includes(). The intent is not immediately clear - you need to understand that
-1 means "not found" and remember the comparison logic.
The .includes() method was specifically designed for existence checks. It clearly expresses the intent: "does this array/string
include this element?" This makes code more readable and self-documenting.
Similarly, using Array#some() for simple equality checks is overkill. The some() method is designed for complex
conditions and predicates. When you only need to check if an element exists, .includes() is more appropriate and can be more performant
since it doesn’t need to execute a callback function.
Using the right method for the right purpose makes code more maintainable and easier to understand for other developers.
This issue affects code readability and maintainability. While it doesn’t cause runtime errors, it makes code harder to understand and review.
Using inappropriate methods can also have minor performance implications, as .indexOf() returns an index that gets discarded, and
Array#some() executes callback functions unnecessarily.
Replace .indexOf() comparisons with .includes(). Instead of checking if the index is not -1 or greater than -1, directly
use .includes() to check existence.
if (array.indexOf('foo') !== -1) { // Noncompliant
// element found
}
if (string.lastIndexOf('bar') >= 0) { // Noncompliant
// element found
}
if (array.includes('foo')) {
// element found
}
if (string.includes('bar')) {
// element found
}