Skip to content

Latest commit

Β 

History

History
80 lines (53 loc) Β· 1.76 KB

consistent-existence-index-check.md

File metadata and controls

80 lines (53 loc) Β· 1.76 KB

consistent-existence-index-check

πŸ“ 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.

Examples

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) {}