DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 2: Polyfill for Array.includes()

Today, let's work on creating a polyfill for Array.includes() method.

NOTE: Polyfills are code snippets that provide modern functionality to older environments that don't support them.

// test cases
const array = [1, 2, 3, 4, 5];

console.log(array.myIncludes(3)); // Output: true
console.log(array.myIncludes(6)); // Output: false

Enter fullscreen mode Exit fullscreen mode

Plan

To solve this problem, we'll follow these steps:

  • Implement the myIncludes function to iterate through the array and check if the given element exists or not.
  • Create a new property called myIncludes on Array.prototype and assign the function.

Check the comment below to see answer.

Top comments (1)

Collapse
 
dhrn profile image
Dharan Ganesan
// Check if Array.prototype.myIncludes exists
if (!Array.prototype.myIncludes) {
  Array.prototype.myIncludes = function (searchElement) {
    // Iterate through each element in the array
    for (let i = 0; i < this.length; i++) {
      // Check if the current element is equal to the search element
      if (this[i] === searchElement) {
        return true;
      }
    }
    // Element not found
    return false;
  };
}

// Test cases
const array = [1, 2, 3, 4, 5];

console.log(array.myIncludes(3)); // Output: true
console.log(array.myIncludes(6)); // Output: false

Enter fullscreen mode Exit fullscreen mode