JS: Array.prototype.includes
(new in JS: ECMAScript 2016)
Array.prototype.includes
xArray.includes(searchElement)
-
- Return
true
if searchElement is in xArray. - Else,
false
.
console.log([3, 4, 5].includes(4)); // true
- Return
xArray.includes(searchElement, fromIndex)
-
Begin search at fromIndex.
console.log([3, 4, 5].includes(3, 1) === false); // true // negative index, search start at end console.log([3, 4, 5].includes(3, -1) === false); // true
Example
On NaN
console.log([3, NaN, 5].includes(NaN));
On undefined
console.log([3, undefined, 5].includes(undefined));
On Sparse Array
const xx = [3, 4]; // make it a sparse array xx.length = 100; // includes finds non-existent element console.log(xx.includes(undefined)); // true
What's the difference between includes vs indexOf
The includes
method differs from
Array.prototype.indexOf
in two ways.