👋🏽 Meet the new Array.at() methodMay 23, 2021JavaScript 295 words

Arrays are one of the widely used data structures in JavaScript. You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array. It’s bonkers.

Today we are going to look at the new Array.at() method. Note that it’s still and experimental feature in Stage 3 Draft1, so browser support is almost nil.2

Why do we need at() method?

The usual way to access items in an array is using the [] notation.

let vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']

vegetables[1]; // => 'Cabbage'

Sometimes you’d want to access the elements from the end of the array instead of the start.

let vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']

vegetables[vegetables.length - 1]; // => 'Carrot'

Now there is nothing wrong with the above approach. JavaScript developers have been using this pattern for ages. And there are libraries like lodash and underscore which provide utility methods to make this simpler.

But it’d be nice to have a native API which allows accessing values using negative indexes. That’s where the new Array.at() method comes in.

Introducing the at() method

Straight from the MDN Docs:3

The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

In simple words, Array.at(index) accesses the element at index. The value of index can be a positive integer (forward lookup) or a negative integer (reverse lookup).

let vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']

vegetables[1]; 		// => 'Cabbage'
vegetables[2];		// => 'Turnip'

vegetables[-1]; 	// => 'Carrot'
vegatables[-2]; 	// => 'Radish'

vegetables[5]; 		// => undefined

The square brackets syntax in JavaScript will still remain the preffered way to access items by index. Just put the index expression in square brackets Array[index], and get the array item at that index. However, Array.at(index) accepts negative values for index, in which case the method takes elements from the end of the array, and therefore no more using the Array.length - index.

This is still an experimental method1, so use the Array.prototype.at polyfill into your application, if you want to start using Array.at() method.