home

includes

The includes() method checks if an array contains a specific value, returning true or false. It uses the SameValueZero equality comparison — meaning it treats NaN as equal to NaN.

This example includes a custom implementation of Array.prototype.includes() with support for optional fromIndex and negative indexing behavior.

function sameValueZero(x, y) {
  return (
    x === y ||
    (typeof x === "number" && typeof y === "number" && x !== x && y !== y)
  );
}
 
Array.prototype.customIncludes = function (searchElement, fromIndex = 0) {
  const length = this.length;
 
  if (length === 0) {
    return false;
  }
 
  if (fromIndex < 0) {
    fromIndex = Math.max(length + fromIndex, 0);
  }
 
  for (let i = fromIndex; i < length; i++) {
    if (sameValueZero(this[i], searchElement)) {
      return true;
    }
  }
 
  return false;
};
 
console.log([1, 2, 3].customIncludes(2)); // true
console.log([1, 2, 3].customIncludes(4)); // false
console.log([1, 2, 3].customIncludes(3, 3)); // false
console.log([1, 2, 3].customIncludes(3, -1)); // true
console.log([1, 2, NaN].customIncludes(NaN)); // true
console.log(["1", "2", "3"].customIncludes(3)); // false
 
const arr = ["a", "b", "c"];
// Since -100 is much less than the array length,
// it starts checking from index 0.
console.log(arr.customIncludes("a", -100)); // true
console.log(arr.customIncludes("a", -2)); // false
console.log(arr.customIncludes("a", -3)); // true