tc39 / proposal-array-last

A JavaScript TC39 Proposal for getting the last element from an array
311 stars 13 forks source link

Is this sugared syntax really necessary? #19

Open calebsander opened 6 years ago

calebsander commented 6 years ago

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.

ljharb commented 6 years ago

It does, however, create an intermediate array (the slice) and invoke the iterable protocol (the destructuring).

stevenwdv commented 2 years ago

Why not use Array.prototype.at(-1) ?

calebsander commented 2 years ago

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.