Enforce consistent style for element existence checks with indexOf()
, lastIndexOf()
, findIndex()
, and findLastIndex()
💼 This rule is enabled in the ✅ recommended
config.
🔧 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.
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) {}