DEV Community

Cover image for Effective use of Array.prototype Methods.
mosemet
mosemet

Posted on

Effective use of Array.prototype Methods.

Array methods are some of the most usefull concepts to master but also quite tricky in what each returns, what it takes as parameters and exactly what does it do to the array.

First defining a prototype. A prototype is a global constructor available for all JavaScript objects and allows the user to add new properties and methods to the array. We can create a new method that provides the sum for an array as follows:

Array.prototype.myArraySum = function () {
     let sum = 0
     for (let i = 0; i < this.length; i++){
         sum += this[i]
        }
         return sum
    }
const array = [1,2,3,5]
console.log(array.myArraySum()) //11
Enter fullscreen mode Exit fullscreen mode

From the example above, we can deduce what a prototype is. It models something, and tells it how to look or behave. A method, is therefore simply a function that is defined on an object. In the example above, the object would be array and the method is myArraySum. It should be noted that myArraySum doesn't take any argument. However most inbuilt JavaScript Array methods take callbacks and other parameters.

A callback function is a function that is applied in another function as an argument, which is then invoked inside the outer function. Let us try to use a callback inside a prototype method:

Array.prototype.someMethod = function (callback) 
    {
       //Do something
       //Return the result
    }
const array = [1,2,3,4]
console.log(array.someMethod(function (a) => { 
  return a*2))
Enter fullscreen mode Exit fullscreen mode

From the example of myArrySum above, we can apply a callback to understand a better on the inner mechanism of prototype methods.

Array.prototype.myArraySum =  function (callback) {
  let bound = callback.bind(this);
    bound();
     let sum = 0
     for (let i = 0; i < this.length; i++){
         sum += this[i]
        }

         return bound(sum)
    }
const array = [1,2,3,5]
console.log(array.myAarraySum((a) => a**2 - 2*a + 7)) //106
Enter fullscreen mode Exit fullscreen mode

Applying a callback to myArraySum gives it more power. The callback does not change what the function does, which is giving a sum of an array, but it can definitely give us flexibility to do something to the sum without extra lines of code. In this case, we have applied a polynomial to indicate the power of callbacks. myArraySum will always return a number, NOT another array. We need to understand what the method returns. That, in my book, is most important when choosing what method to use.

JavaScript has inbuilt Array.prototype methods, which can be accessed on this link.

A deeper dive of these array methods will be explored in these series.

Top comments (0)