Skip to content

Latest commit

 

History

History
119 lines (87 loc) · 2.49 KB

prefer-includes.md

File metadata and controls

119 lines (87 loc) · 2.49 KB

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

💼 This rule is enabled in the ✅ recommended config.

🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

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

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

array.indexOf('foo') !== -1;
array.indexOf('foo') !== -1;
string.lastIndexOf('foo') !== -1;
array.lastIndexOf('foo') !== -1;
foo.indexOf('foo') != -1;
foo.indexOf('foo') >= 0;
foo.indexOf('foo') > -1;
foo.indexOf('foo') === -1
foo.some(x => x === 'foo');
foo.some(x => 'foo' === x);
foo.some(x => {
	return x === 'foo';
});

Pass

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