The includes() method determines whether an array includes a certain value, returning true or false.
β Implementation
Array.prototype.customIncludes = function (searchElement, fromIndex = 0) { if (fromIndex < 0) { fromIndex = Math.max(this.length + fromIndex, 0); } for (let i = fromIndex; i < this.length; i++) { if (this[i] === searchElement || (Number.isNaN(this[i]) && Number.isNaN(searchElement))) { return true; } } return false; }; // Example usage: const array = [1, 2, 3]; console.log(array.customIncludes(2)); // Output: true console.log(array.customIncludes(4)); // Output: false console.log(array.customIncludes(3, -1)); // Output: true console.log(array.customIncludes(1, -3)); // Output: true console.log([NaN].customIncludes(NaN)); // Output: true
How It Works:
- Parameters :
searchElement: The element to search for in the array.fromIndex: The index to start the search from (defaults to 0). Negative values are adjusted to count from the end of the array.
- Iteration : The
customIncludesmethod iterates through the array starting fromfromIndex. - Comparison : For each element, it checks if the element is strictly equal (
===) tosearchElementor if both areNaN. - Return Value :
- Returns
trueifsearchElementis found. - Returns
falseifsearchElementis not found.
- Returns
Example:
customIncludes(2)returnstruebecause2is in the array.customIncludes(4)returnsfalsebecause4is not in the array.customIncludes(3, -1)returnstruebecause3is found when counting from the end.customIncludes(1, -3)returnstruebecause1is found when counting from the end.[NaN].customIncludes(NaN)returnstruebecauseNaNis found in the array.
Key Features:
- Supports negative
fromIndexby adjusting it to count from the end of the array. - Iterates through the array and checks for strict equality (
===) withsearchElementor if both areNaN. - Returns a boolean indicating whether
searchElementis found in the array.
Quick Quiz
Test your understanding with 3 quick questions
Q1What does `[NaN].customIncludes(NaN)` return?
Q2How does `includes()` differ from `indexOf()` when dealing with NaN?
Q3What does `[1, 2, 3].customIncludes(2, 2)` return?