Array.at() Will Change How We Access Array Values in JavaScript

How to access negative indexes in JavaScript, and how this could change with Array.prototype.at()

Akash Thakur
JavaScript in Plain English

--

Photo by La-Rel Easter on Unsplash

There are times when I felt a dire need to access array elements from reverse, maybe the last item or the second last.

The way to go about it was never straightforward like it is in some other languages where you can just say array[-1] and it gives you the last item.

Instead we have to do things like array[array.length-1] and so on.

The [] syntax is not specific to Arrays and Strings; it applies to all objects. Referring to a value by index, like array[1], actually just refers to the property of the object with the key 1, which is something that any object can have. So array[-1] already “works” in today’s code, but it returns the value of the -1 property of the object, rather than returning an index counting backwards from the end.

Accessing elements

Trying to get a value for an index which isn’t present in the array will return undefined in JavaScript.

const arr=['a', 'b', 'c', 'd', 'e'];arr[1] // barr[4] // earr[-1] // undefined

What are the options here to access the last element, currently we can do arr[arr.length — 1] or arr.slice(-1)[0] and this would give us e as an output for the above array.

Proposed Property — “at”

With this new property, accessing elements in array is going to become convenient going forward.

The way we access values isn’t going to change with at but accessing negative indexes will become easy. Here’s how it would look:

const arr=['a', 'b', 'c', 'd', 'e'];arr.at(1) // barr.at(4) // earr.at(-1) // earr.at(10) // undefined

Conclusion

Hopefully this will move forward to Stage 4 soon and be officially adopted. I am quite excited about this one and can see this becoming a syntactic sugar for accessing array elements.

There’s also a last property being in discussion (accessing last element of an array/string) but it’s still in stage 1 and might well be dropped in favour of this new property at as it’s already stage 3 and solves the same purpose and much more.

More content at plainenglish.io

--

--

JS Enthusiast. Eager to learn and share knowledge on HTML | CSS | Javascript | React | Angular | Node | GraphQL and other web technologies.