Implement a custom function similar to Array.prototype.includes() method using JavaScript


Problem

We are required to write a JavaScript function that lives on the prototype object of Array.It must take in a literal value, and return true if that value is present in the array it is being called upon, false otherwise.

Example

Following is the code −

 Live Demo

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const num = 6;
Array.prototype.customIncludes = function(num){
   for(let i = 0; i < this.length; i++){
      const el = this[i];
      if(num === el){
         return true;
      };
   };
   return false;
};
console.log(arr.customIncludes(num));

Output

true

Updated on: 17-Apr-2021

871 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements