proposal-array-last
proposal-array-last copied to clipboard
Is this sugared syntax really necessary?
With ES2015 array destructuring, I find that let [lastItem] = arr.slice(-1)
is a nice way to access the last item. It is hard to make a mistake with this syntax, which I think defeats all the reasons given in the rationale section of the README. It also has the benefit of not referencing arr
twice, which means you can use it as let [lastItem] = someComplexExpressionToComputeArr().slice(-1)
. Without destructuring, you can still use arr.slice(-1)[0]
, which is only 4 characters longer than arr.lastItem
.
It does, however, create an intermediate array (the slice) and invoke the iterable protocol (the destructuring).
Why not use Array.prototype.at(-1)
?
Why not use
Array.prototype.at(-1)
?
That method didn't exist in the ECMAScript spec 4 years ago, but looks like it solves the issue pointed out above.