Using Javascript prototypal inheritance to add an Array search method

Javascript has no classes. Everything is an object in Javascript. Even functions. And objects can inherit other objects.

In this post, I will show how to use this unique inheritance feature of Javascript, aka prototypal inheritance, to customize built in Javascript objects like arrays. Particularly, I will show how to add a custom method to the Javascript Array object so that any array you use in your javascript app can use that method.

 

Whenever you create a new array in Javascript, it is an object inheriting from the Array object. Our target is to add a search method to the Array object. Wouldn’t it be convenient to be able to search arrays like

var result = myArray.find("Mango");

 

Well, wouldn’t it?

 

You bet it will be. But Javascript arrays do not come with a find method. Let us put it into the Array object so that all arrays can use it.

 

Array.prototype.find = function(key, value)
{
   var i;

   if(!key && !value)
   {
      return this;   //return the whole array since no parameters are passed
   }

   for(i = 0; i < this.length; i++)
   {
      if(!value)
      {
         //if only one parameter is passed, it will be found as key, value will be null

         value = key;

         if(this[i] == value) return this[i];
      }
      else
      {
         if(this[i][key] == value) return this[i];
      }
   }

   return null;
}

The code has been generalized to work for both complex objects in the target array, as well as simple arrays like an array of strings. If your array has complex objects then obviously you have to pass an extra parameter to the search function telling which property of an object will be searched for a matching value.

 

The use of the keyword prototype in the function declaration makes this function available to all sub-objects of Array, i.e. all arrays in your Javascript app. In the same way, you could add a variable to Array. And you can put any object before the prototype keyword. That is the beauty of Javascript’s prototypal inheritance; the hierarchy can start from anywhere.

 

If you have ever worked with ArrayLists or Vectors in C# or Java (these are expandable arrays, for those who do not know), you will have noticed that ArrayList or Vector class comes in with lots and lots of helper methods like toString(), find() for manipulating the arrays. Javascript does not give you so many helper methods built-in. But using prototypal inheritance, you can very easilly add helper methods like these and make your arrays more fun to use.

Leave a comment