DEV Community

Discussion on: `at` coming soon to ECMAScript

Collapse
 
nickytonline profile image
Nick Taylor • Edited

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

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
</div>
Enter fullscreen mode Exit fullscreen mode

Collapse
 
davwheat profile image
David Wheatley

Oooh I knew this was possible, but never really put 2 and 2 together with that destructuring for the last item! Thanks for pointing that out to me.

Collapse
 
nickytonline profile image
Nick Taylor • Edited

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

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
Collapse
 
milichev profile image
Vadym Milichev • Edited

This const [, last] = someArray is equal to const last = someArray[1]
To use destructuring, one might want something like
const [l, [l - 1]: last] = someArray, but it's hardly more readable 😁

Collapse
 
sybers profile image
Stanyslas Bres

@milichev I get the idea from your snippet but I think the syntax is incorrect, it should look something like this :

const { length, [length - 1]: last } = [1, 2, 3, 4];
// last === 4
Enter fullscreen mode Exit fullscreen mode

Anyways that's a funny thing I never thought of :)

Collapse
 
rpcabrera profile image
Rigoberto • Edited

Even I propose to extend your idea and include all quick methods related to collections like LINQ (from C#) does.