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)); // trueconsole.log([1, 2, 3].customIncludes(4)); // falseconsole.log([1, 2, 3].customIncludes(3, 3)); // falseconsole.log([1, 2, 3].customIncludes(3, -1)); // trueconsole.log([1, 2, NaN].customIncludes(NaN)); // trueconsole.log(["1", "2", "3"].customIncludes(3)); // falseconst 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)); // trueconsole.log(arr.customIncludes("a", -2)); // falseconsole.log(arr.customIncludes("a", -3)); // true