Array.prototype.includesLoading saved progress…

Array.prototype.includes

Array.prototype.includes answers "is this value in the array?" with a plain true or false. Its one subtlety is how it compares: it uses SameValueZero, which is like === except that NaN matches NaN — so includes can find a NaN that indexOf never will.

Implement arrayIncludes(arr, value, fromIndex). Scan from fromIndex (default 0) to the end and return true if any element equals value under SameValueZero. A negative fromIndex counts back from the end.

Signature

function arrayIncludes(arr, value, fromIndex) {
  // returns true if `value` is found at or after fromIndex, using
  // SameValueZero equality (=== but NaN matches NaN); false otherwise.
}

Examples

arrayIncludes([1, 2, 3], 2);    // true
arrayIncludes([1, NaN, 3], NaN); // true  — indexOf would say -1 (not found)
arrayIncludes([1, 2, 1], 1, 1); // true  — start at index 1, find the second 1
arrayIncludes([1, 2, 3], 3, -1); // true — fromIndex -1 starts at the last element

Notes

  • SameValueZero — the same as ===, with one exception: NaN is considered equal to NaN. (+0 and -0 are still equal, as with ===.)
  • fromIndex — defaults to 0. A negative value resolves to arr.length + fromIndex; if that's still negative, clamp to 0 (search the whole array).
  • Objects compare by reference — two different objects with the same shape are not equal. This is not a deep comparison.
  • Holes are not skipped — unlike forEach, includes reads a hole as undefined, so includes(arr, undefined) can match one.
  • Returns a boolean — not an index. Use indexOf when you need the position.
Loading editor…