Skip to content

Latest commit

 

History

History
58 lines (43 loc) · 1.5 KB

prefer-array-index-of.md

File metadata and controls

58 lines (43 loc) · 1.5 KB

Prefer Array#indexOf() over Array#findIndex() when looking for the index of an item

Array#findIndex() is intended for more complex needs. If you are just looking for the index where the given item is present, then the code can be simplified to use Array#indexOf(). 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 has side effects.

Fail

const index = foo.findIndex(x => x === 'foo');
const index = foo.findIndex(x => 'foo' === x);
const index = foo.findIndex(x => {
	return x === 'foo';
});

Pass

const index = foo.indexOf('foo');
const index = foo.findIndex(x => x == undefined);
const index = foo.findIndex(x => x !== 'foo');
const index = foo.findIndex((x, index) => x === index);
const index = foo.findIndex(x => (x === 'foo') && isValid());
const index = foo.findIndex(x => y === 'foo');
const index = foo.findIndex(x => y.x === 'foo');
const index = foo.findIndex(x => {
	const bar = getBar();
	return x === bar;
});