Adding a getter to Array.prototype

Viewed 970

I wanted to add a getter to Array.prototype to get the last element of the array.

I did it like this:

Object.defineProperty(Array.prototype, 'last', {
    get: function() {
        return this[this.length - 1];
    }
});

Is this proper for memory? My worry was if you instance 10000 objects:

  • I hope I will only have 1 functions in the memory
  • My worry is that I might have 10000 * 1 = 10000 functions in the memory

My goal is to use it like this:

const arr = [{}, {}, {}, {}];
arr.last === arr[arr.length - 1];
3 Answers

The problem with modifying prototypes of base-classes is that if you do it, other people could do it too and then combining code from multiple authors the versions might silently conflict. Somebody else's version of the method last() might override yours without you realizing it, and might return a different result than you expect, without you realizing it.

A better way in my opinion is to provide a simple way to create a wrapper -object around arrays on demand, the wrapper-object then has methods like last() which returns the last element of the now wrapped array inside it. It could look this:

w ([1, 2, 3]).last()

More on the wrapper-approach especially as applied to the last() -method for Arrays see: https://medium.com/@panuviljamaa/why-javascript-needs-the-method-last-9f4e285f3f7d

Related