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.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.last can really improve clarity.
Suggestions of properties like