Getting an item an array with a negative index with modern JavaScript
Today, we’re going to look at the Array.prototype.at()
method: what it does, how it works, and why you might want to use it over simple bracket notation.
Let’s dig in!
Getting an array item by its index
The Array.prototype.at()
method gets an array item at a specific index. Pass the index in as an argument.
Let’s imagine you have an array of wizards
…
let wizards = ['Merlin', 'Ursula', 'Ragadast', 'Gandalf'];
You can use the Array.prototype.at()
method to get the item at index 2
like this…
// returns "Ragadast"
let radagast = wizards.at(2);
Why would you use this over bracket notation?
JavaScript already provides a way to get items by their index: bracket notation.
// returns "Ursula"
let ursula = wizards[1];
So… why would you use the Array.prototype.at()
method instead of bracket notation?
The Array.prototype.at()
method has one advantage over bracket notation: it supports negative indexes.
If you used an index of -1
with bracket notation, you get undefined
as the returned value.
// returns undefined
let maybeGandalf = wizards[-1];
But with the Array.prototype.at()
method, negative indexes are counted backwards from the end of the array. An index of -1
returns Gandalf
instead.
let gandalf = wizards.at(-1);