JS: Array.prototype.includes

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2016)

Array.prototype.includes

xArray.includes(searchElement)

Return true if searchElement is in xArray. Else, false.

console.assert([3, 4, 5].includes(4));
xArray.includes(searchElement, fromIndex)

Begin search at fromIndex, can be negative.

console.assert(["x", 4, 5].includes("x", 0));

console.assert(["x", 4, 5].includes("x", 1) === false);
// negative index, search start at end
console.assert([3, 4, 5].includes(3, -1) === false);

Edge Case Examples

On NaN

JS: NaN

console.assert([3, NaN, 5].includes(NaN));

On undefined

JS: undefined

console.assert([3, undefined, 5].includes(undefined));

On Sparse Array

JS: Sparse Array

const xx = [3, 4];
// make it a sparse array
xx.length = 100;

// includes finds non-existent element
console.assert(xx.includes(undefined));

What's the difference between includes vs indexOf

Array.prototype.indexOf:

Array.prototype.includes:

JavaScript. Array Search