Skip to content

Latest commit

 

History

History
115 lines (85 loc) · 2.51 KB

prefer-includes.md

File metadata and controls

115 lines (85 loc) · 2.51 KB

Prefer .includes() over .indexOf() and Array#some() when checking for existence or non-existence

This rule is part of the recommended config.

🔧💡 This rule is auto-fixable and provides suggestions.

All built-ins have .includes() in addition to .indexOf(). Prefer .includes() over comparing the value of .indexOf().

Array#some() is intended for more complex needs. If you are just looking for the index where the given item is present, the code can be simplified to use Array#includes(). This applies to any search with a literal, a variable, or any expression that doesn't have any explicit side effects. However, if the expression you are looking for relies on an item related to the function (its arguments, the function self, etc.), the case is still valid.

This rule is fixable, unless the search expression in Array#some() has side effects.

Fail

[].indexOf('foo') !== -1;
x.indexOf('foo') != -1;
str.indexOf('foo') > -1;
'foobar'.indexOf('foo') >= 0;
x.indexOf('foo') === -1
const isFound = foo.some(x => x === 'foo');
const isFound = foo.some(x => 'foo' === x);
const isFound = foo.some(x => {
	return x === 'foo';
});

Pass

const str = 'foobar';
str.indexOf('foo') !== -n;
str.indexOf('foo') !== 1;
!str.indexOf('foo') === 1;
!str.indexOf('foo') === -n;
str.includes('foo');
[1,2,3].includes(4);
const isFound = foo.includes('foo');
const isFound = foo.some(x => x == undefined);
const isFound = foo.some(x => x !== 'foo');
const isFound = foo.some((x, index) => x === index);
const isFound = foo.some(x => (x === 'foo') && isValid());
const isFound = foo.some(x => y === 'foo');
const isFound = foo.some(x => y.x === 'foo');
const isFound = foo.some(x => {
	const bar = getBar();
	return x === bar;
});