`at` coming soon to ECMAScript

Laurie - Jun 14 '21 - - Dev Community

If you're a JavaScript developer you've likely used arrays quite a bit. They're an essential data structure within the language.

In fact, they're so essential that the array prototype has seen rapid expansion in the past few years, with things like flat and filter added. And we're not done yet.

Accessor

In order to access an element in an array, you need to know its index. Indeces in JavaScript are zero-based, so the first element is at index 0.

const arr = ["a","b","c","d"]
arr[0] // this is "a"
arr[2] // this is "c"
Enter fullscreen mode Exit fullscreen mode

As you can see in the example above, you can access the first element, or the third element. What about the last element? In other languages you might be able to do something like this.

const arr = ["a","b","c","d"]
arr[-1] // This is NOT "d"
Enter fullscreen mode Exit fullscreen mode

But not in JavaScript! Why not? Well, as it turns out, -1 is already a valid key. Arrays are really objects with indeces as keys. So arr[-1] is looking at the arr object and the value of the "-1" key, which is undefined.

The last element

Then how do we access the last element without knowing its index? There are ways to do it, but its certainly more verbose. You can use the length lookup.

arr[arr.length - 1] // this is "d"
Enter fullscreen mode Exit fullscreen mode

Or you have the slice option.

arr.slice(-1)[0] // this is "d"
Enter fullscreen mode Exit fullscreen mode

Introducing at

That's why the at function is under consideration. Instead of those options, you'd be able to write this instead.

arr.at(-1) // this is "d"
Enter fullscreen mode Exit fullscreen mode

Note that this works for all valid negative indices, up until you pass the first element.

The great thing about at is that it can replace square brackets all together.

arr.at(0) // this is still "a"
Enter fullscreen mode Exit fullscreen mode

And what about an invalid index?

arr.at(5) // this is undefined
Enter fullscreen mode Exit fullscreen mode

Seems pretty all encompassing.

An aside on history

As it turns out, this was attempted before using item. However, it wasn't web compatible as it clashed with major libraries. So, at is the current proposal.

Would you use it?

Hopefully this will move forward to Stage 4 soon and be officially adopted. I can see this being nice syntactic sugar for accessing array elements.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .