Open calebsander opened 6 years ago
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.
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 referencingarr
twice, which means you can use it aslet [lastItem] = someComplexExpressionToComputeArr().slice(-1)
. Without destructuring, you can still usearr.slice(-1)[0]
, which is only 4 characters longer thanarr.lastItem
.