Proposal: Array.prototype.first() and Array.prototype.last()

Nicu Micleusanu micnic90 at gmail.com
Tue Sep 27 13:08:47 UTC 2016


Well, `String.prototype.match()` does this, it returns an array of 
matches or `null` in case there are no matches. I agree that in some 
situation this can be a source of errors, but the implementation would 
be quite useful.

In case it's not acceptable, I would propose read-only members 
`Array.prototype.first` and `Array.prototype.last`:

```js
Object.defineProperties(Array.prototype, {
     first: {
         get: function () {
             return this[0];
         }
     },
     last: {
         get: function () {
             if (this.length) {
                 return this[this.length - 1];
             } else {
                 return void 0;
             }
         }
     }
});
```


More information about the es-discuss mailing list