Why doesn't JavaScript have a last method?

You can do something like this:

[10, 20, 30, 40].slice(-1)[0]

console.log([10, 20, 30, 40].slice(-1)[0])

The amount of helper methods that can be added to a language is infinite. I suppose they just haven't considered adding this one.


It's easy to define one yourself. That's the power of JavaScript.

if(!Array.prototype.last) {
    Array.prototype.last = function() {
        return this[this.length - 1];
    }
}

var arr = [1, 2, 5];
arr.last(); // 5

However, this may cause problems with 3rd-party code which (incorrectly) uses for..in loops to iterate over arrays.

However, if you are not bound with browser support problems, then using the new ES5 syntax to define properties can solve that issue, by making the function non-enumerable, like so:

Object.defineProperty(Array.prototype, 'last', {
    enumerable: false,
    configurable: true,
    get: function() {
        return this[this.length - 1];
    },
    set: undefined
});

var arr = [1, 2, 5];
arr.last; // 5

Because Javascript changes very slowly. And that's because people upgrade browsers slowly.

Many Javascript libraries implement their own last() function. Use one!

Tags:

Javascript