JS: Array.prototype.includes

By Xah Lee. Date: . Last updated: .

New in ES2016.

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

fromIndex defaults to 0.

fromIndex can be negative. If negative, index count from right to left starting at last element.

The includes method intentionally differs from the similar indexOf method in two ways. First, it uses the SameValueZero algorithm, instead of Strict Equality Comparison, allowing it to detect NaN array elements. Second, it does not skip missing array elements, instead treating them as undefined.

[see JS: NaN]

const rr = [3,4,5];

console.log ( rr.includes (4) === true ); // true

NaN example:

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

undefined example:

console.log (
    [3,undefined,5].includes(undefined) === true
); // true

Sparse array example:

const arr = [3,4];

arr.length = 100;

console.log (
    arr.includes(undefined) === true
); // true

console.log (
    arr.indexOf ( undefined ) === -1
); // true

[see JS: Sparse Array]

Reference

ECMAScript® 2016 Language Specification#sec-array.prototype.includes

Array Search Topic

  1. JS: Array.prototype.indexOf
  2. JS: Array.prototype.lastIndexOf
  3. JS: Array.prototype.find
  4. JS: Array.prototype.findIndex
  5. JS: Array.prototype.includes

Array Topic

  1. JS: Array Basics
  2. JS: Understand JS Array
  3. JS: Create Array
  4. JS: Sparse Array
  5. JS: Array-Like Object
  6. JS: Array How-To
  7. JS: Array Object
  8. JS: Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Patreon me $5. Ask me question on patreon