The Array.prototype.includes() Method
You might recall that ECMAScript 6 added String.prototype.includes()
in order to check whether certain substrings exist within a given string. Originally, ECMAScript 6 was also going to introduce an Array.prototype.includes()
method to continue the trend of treating strings and arrays similarly. But the specification for Array.prototype.includes()
was incomplete by the ECMAScript 6 deadline, and so Array.prototype.includes()
ended up in ECMAScript 2016 instead.
How to Use Array.prototype.includes()
The Array.prototype.includes()
method accepts two arguments: the value to search for and an optional index from which to start the search. When the second argument is provided, includes()
starts the match from that index. (The default starting index is 0
.) The return value is true
if the value is found inside the array and false
if not. For example:
let values = [1, 2, 3];
console.log(values.includes(1)); // true
console.log(values.includes(0)); // false
// start the search from index 2
console.log(values.includes(1, 2)); // false
Here, calling values.includes()
returns true
for the value of 1
and false
for the value of 0
because 0
isn’t in the array. When the second argument is used to start the search at index 2 (which contains the value 3
), the values.includes()
method returns false
because the number 1
is not found between index 2 and the end of the array.
Value Comparison
The value comparison performed by the includes()
method uses the ===
operator with one exception: NaN
is considered equal to NaN
even though NaN === NaN
evaluates to false
. This is different than the behavior of the indexOf()
method, which strictly uses ===
for comparison. To see the difference, consider this code:
let values = [1, NaN, 2];
console.log(values.indexOf(NaN)); // -1
console.log(values.includes(NaN)); // true
The values.indexOf()
method returns -1
for NaN
even though NaN
is contained in the values
array. On the other hand, values.includes()
returns true
for NaN
because it uses a different value comparison operator.
W> When you want to check just for the existence of a value in an array and don’t need to know the index , I recommend using includes()
because of the difference in how NaN
is treated by the includes()
and indexOf()
methods. If you do need to know where in the array a value exists, then you have to use the indexOf()
method.
Another quirk of this implementation is that +0
and -0
are considered to be equal. In this case, the behavior of indexOf()
and includes()
is the same:
let values = [1, +0, 2];
console.log(values.indexOf(-0)); // 1
console.log(values.includes(-0)); // true
Here, both indexOf()
and includes()
find +0
when -0
is passed because the two values are considered equal. Note that this is different than the behavior of the Object.is()
method, which considers +0
and -0
to be different values.