proposal-array-last icon indicating copy to clipboard operation
proposal-array-last copied to clipboard

Is this sugared syntax really necessary?

Open calebsander opened this issue 6 years ago • 3 comments

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.

calebsander avatar Jul 24 '18 20:07 calebsander

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

ljharb avatar Jul 24 '18 22:07 ljharb

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

stevenwdv avatar Jul 12 '22 13:07 stevenwdv

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.

calebsander avatar Jul 12 '22 13:07 calebsander