Array.prototype.indexOf() methods have the following differences:
|Primary Use:||Check if array includes given element.||Get the position of the first match (of given element) in the array.|
|Return Type:||Boolean (
||Number (matching index if match found, or
|Handling of Special Cases:||
The following return
The following return
Array.prototype.includes() was created for the specific purpose of checking if the array includes the given element among its entries or not.
Array.prototype.indexOf() is commonly used to determine if an array includes an element, its primary use is to actually get the index of the first match in an array.
It returns boolean
false depending on whether an element was found in the array or not. For example:
['foo', 'bar'].includes('bar'); // true ['foobar'].includes('bar'); // false [1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false
It returns the first index at which a given element is found in the array, or
-1 otherwise. For example:
['foo', 'bar'].indexOf('bar'); // 1 ['foobar'].indexOf('bar'); // -1 [1, 2, 3].indexOf(2); // 1 [1, 2, 3].indexOf(4); // -1
Handling of Special Cases
Array.prototype.includes() uses the
SameValueZero comparison algorithm, while
Array.prototype.indexOf() uses the
Strict Equality Comparison algorithm. Therefore, they both differ in the handling of some special cases as demonstrated in the following examples:
[NaN].includes(NaN); // true [NaN].indexOf(NaN) > -1; // false
Handling of Array With Empty Slots:
length but no values (note that this is not the same as slots with actual
undefined values). In such cases,
indexOf() will skip the empty slots while
includes() won't. For example:
const emptyArr1 = [ , , ]; const emptyArr2 = new Array(3); emptyArr1.includes(undefined); // true emptyArr1.indexOf(undefined) > -1; // false emptyArr2.includes(undefined); // true emptyArr2.indexOf(undefined) > -1; // false
In contrast to this, checking for
undefined in an array with explicitly defined
undefined values would yield the same result for both methods. For example:
[1, 2, undefined].includes(undefined); // true [1, 2, undefined].indexOf(undefined) > -1; // true
- Introduced in ES7;
- Widely supported in modern browsers.
- Introduced in ES5;
- Good compatibility with older browsers.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.