In fact, they're so essential that the array prototype has seen rapid expansion in the past few years, with things like
filter added. And we're not done yet.
const arr = ["a","b","c","d"] arr // this is "a" arr // this is "c"
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"
-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
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"
Or you have the slice option.
arr.slice(-1) // this is "d"
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"
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"
And what about an invalid index?
arr.at(5) // this is undefined
Seems pretty all encompassing.
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.
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.