DEV Community

Discussion on: Introducing `findLast` and `findLastIndex`

Collapse
 
nickytonline profile image
Nick Taylor

Yes! It’s like my dream came true when I asked for it in your other post lol.

I've used var last = arr[arr.length - 1] in the past, but now with destructuring, I typically do const [, last] = someArray.

I'm not sure I'd use at aside from getting the last item in an array since currently I can do
e.g. someArray[1] which is less typing than someArray.at(1) for elements that are not the last item. I probably would have opted for an Array.prototype.last.

Maybe there are use cases for it that I'm missing like composing a bunch of functions.

Not everyone is seeing my addendum to this comment so here it is

Just an update to my initial comment as I typed it out pretty quickly yesterday. const [, last] = someArray will work if the array was only two items. For example, if it's 4 items, this won't work. You'll end up with this.

const a = [1,2,3,4];
const [,last] = a;

console.log(last); // a === 2
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode


Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode

Enter fullscreen mode Exit fullscreen mode

If I wanted to get the last element in the above array, I'd have to do this.

const a = [1,2,3,4];
const [, , ,last] = a;

console.log(last); // a === 2
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode


Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode

Enter fullscreen mode Exit fullscreen mode
</div>
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode

Enter fullscreen mode Exit fullscreen mode


</div>
Enter fullscreen mode Exit fullscreen mode

Collapse
 
laurieontech profile image
Laurie

That post is far too noisy. I lost track of comments many days ago.