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.log([3, 4, 5].includes(4));
// true
xArray.includes(searchElement, fromIndex)

Begin search at fromIndex, can be negative.

console.log(["x", 4, 5].includes("x", 0));
// true

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

Example

On NaN

JS: NaN

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

On undefined

JS: undefined

console.log([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.log(xx.includes(undefined));
// true

What's the difference between includes vs indexOf

Array.prototype.indexOf:

Array.prototype.includes:

JavaScript. Array Search