π Enforce consistent style for element existence checks with indexOf(), lastIndexOf(), findIndex(), and findLastIndex().
πΌ This rule is enabled in the following configs: β
recommended, βοΈ unopinionated.
π§ This rule is automatically fixable by the --fix CLI option.
Enforce consistent style for element existence checks with indexOf(), lastIndexOf(), findIndex(), and findLastIndex().
Prefer using index === -1 to check if an element does not exist and index !== -1 to check if an element does exist.
The value -1 is the sentinel returned by these methods when no match is found, so comparing it directly with === or !== makes the check read as a not-found sentinel check instead of a numeric range check.
Similar to the explicit-length-check rule.
const index = foo.indexOf('bar');
// β
if (index < 0) {}
// β
if (index === -1) {}const index = foo.indexOf('bar');
// β
if (index >= 0) {}
// β
if (index !== -1) {}const index = foo.indexOf('bar');
// β
if (index > -1) {}
// β
if (index !== -1) {}const index = foo.lastIndexOf('bar');
// β
if (index >= 0) {}
// β
if (index !== -1) {}const index = array.findIndex(element => element > 10);
// β
if (index < 0) {}
// β
if (index === -1) {}const index = array.findLastIndex(element => element > 10);
// β
if (index < 0) {}
// β
if (index === -1) {}