I recently read a post here on dev about the consideration of .at()
implementation in JS.
If you don't want to read the original post (you should) here's a little recap.
.at()
As far as I get this new function can be used as a replacemente for the classic []
if used with a positive index but can also access elements in reverse order if used with negative index.
Eg.
const arr = [ 'a', 'b', 'c', 'd'];
arr.at(0); // 'a'
arr.at(3); // 'd'
arr.at(4); // undefined
arr.at(-1); // 'd'
arr.at(-4); // 'a'
arr.at(-5); // undefined
Just looking at this (pun intended) show to me that .at(-1)
is a sugar syntax to get the last element of an array without using .length
nor .slice()
.
Doubts
I still have to dig deeper but I already have a couple of doubts.
How oftend do we need it?
.at(-1)
can be useful (and a lot of languages has something to get the last item) but how often do you need to get the second or third last item? I image as often as you need the second or the third so not so much.
Loop in reverse order
You (or at least someone) could think that it can be handy for looping in a reverse order. An out of bound index return undefined
so it should be easy, right? Well, no because array can have undefined element even in the middle
const arr = ['a', undefined, 'c'];
so we still have to rely on the old way with
for (let i = 1; i <= arr.length; i++) {
const item = arr.at(-i);
}
very much like
for (let i = arr.length - 1 ; i >= 0; i--) {
const item = arr[i];
}
or in a simpler way
for (const item of arr.slice().reverse()) {
The examples are from the comments written by Henry Ing-Simmons on the original post.
Negative index
I know, I know. Javascript allow only non negative index in arrays but we all knows that sometimes it allows some crazy shit like
const arr=[];
arr[-1]="a";
arr[0] ="b";
arr[1] ="c";
console.log(arr); // ["b", "c"]
console.log(arr[-1]); // "a"
Obviosuly it's not black magic but it's just creating a property -1
for the object arr
// do you remember that
const arr=[];
console.log(typeof(arr)); // object
Ok, this one was just to screwing around and keep you from falling asleep while reading my post.
Recap
IMHO .at()
will be used just to get the last item of an array.
If you think I'm missing something I urge you to point me in the right direction because I'm struggling on my own in finding a real purpouse for .at()
Top comments (2)
I think it can be useful for functional programming. Since
.at()
is already a function it can be passed around where callbacks are expected, where as using standard[]
needs to at least be wrapped into an arrow function. I think this usage would still be pretty rare though!I didn't even think about that. It's a good example but still an edge case.