A recent TC39 proposal offers easier access to the last element in a JavaScript Array. While on the surface this does not seem significant, there are many benefits to such a proposal.
Terminal elements are unique in that they tend to be accessed more often than middle elements. Because of this, many other scripting languages like Ruby and Python provide convenience methods and properties to access and modify them.
The only way to do this in ES6 is with indices. But even a trivial task like swapping the last elements in two arrays quickly becomes difficult to read.
The most common solution today is to use libraries like Lodash or Underscore that include utility functions for accessing the last element. This offers an improvement in clarity, but introduces several complications. Most obviously, they do not include a way to set the last element. Even if they did, doing so would add ambiguity by removing the =
assignment operator.
That is where the ECMAScript Technical Candidate (TC39) proposal comes in. In its current form, it introduces two new properties: Array.lastItem
and Array.lastIndex
. The first property is especially useful because it works both for setting and getting the last item.
This proposal is actually already supported in core-js 3 and can be used with Babel and TypeScript today. However, I do not have much use for Array.lastIndex
and would prefer a symmetrical for the first element. For prototypes and smaller projects I wrote two simple, dependency-free properties that do just that.
I recently learned that destructuring in ES6 can swap array elements without temporary variables. This is a great example of where Array.first
and Array.last
can really improve clarity.
Suggestions of properties like Array.first
and Array.last
go back to at least 2013. Hopefully this Stage 1 proposal continues to get traction and will be coming to a version of JavaScript near you soon.
Top comments (3)
Array.last is on pause in favor of a few other proposals...
Array.first
andArray.last
are interesting proposals. Thanks for the clear examples. I've always thought Python's[-1]
accessor for the last element was very elegant.Thanks for the kind words. I'm mixed on negative indices. They are more powerful than a single
Array.last
property because they let you easily access say, the second to last element[-2]
. But I don't find them that much clearer.That said, JavaScript will likely never get support for negative indices because Array is just an Object, and
[-1]
is a valid property on either. This would introduce a break change to the language (although it's a pretty bad idea using an Array as a map).