views:

92

answers:

4

Its kinda weird Javascript Array class does not offer last method to retrieve the last element of array. I know the solution is too simple (Ar[Ar.length-1] ) but still this is too frequently used.

Any serious reasons why this is not incorporated yet?

+6  A: 

It's easy to define one yourselves. That's the powa of JavaScript.

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

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

Or if you are not bound with browser support problems, then use the new ES5 syntax to define properties. Chrome and Firefox nightly only at the moment.

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
Anurag
note that adding properties to Array's prototype can break code where for..in is used to iterate over an array. Using for..in to iterate an array is bad practice, but it's done commonly enough that altering Array's prototype is also bad practice. In general, prototypes of Object, Array, String, Number, Boolean, and Date should not be altered if your script needs to work with other unknown code.
no
@no - Thanks for the tip. I should've mentioned that the reason for adding the ES5 syntax with enumerability set to false was precisely to solve the `for..in` problem. Sure, we're not there yet with a wide implementation of ES5, but it's good enough to know now as browsers are catching up to it fast, including IE9.
Anurag
+2  A: 

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

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

Triptych
+1  A: 
Array.prototype.last = Array.prototype.last || function() {
    var l = this.length;
    return this[l-1];
}

x = [1,2];
alert( x.last() )
meder
What should be appropriate output for [].last()? `null` or `undefined`?
Álvaro G. Vicario
probably undefined to keep it consistent language-wise.
meder
null I think- because you do have an array well defined- just that there are no valid objects in it.undefined should be used only when last 'property' is not defined on the called container.
Nikhil Garg
just returning `this[l-1]` would give you `undefined` as is normal for accessing non-existent properties. Personally I'd rather JS threw an exception rather than returning `undefined`, but JS prefers to sweep errors under the rug.
bobince
+4  A: 

You can do something like this:

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

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

Álvaro G. Vicario
tempted to downvote for "close to infinity"
Triptych
Why? You can get as close as you want, no limit :)
Álvaro G. Vicario