The usual way to access items in an array is using the
let vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'] vegetables; // => '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'
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.
Straight from the MDN Docs:3
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; // => 'Cabbage' vegetables; // => 'Turnip' vegetables[-1]; // => 'Carrot' vegatables[-2]; // => 'Radish' vegetables; // => undefined
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.