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
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
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?
// returns "Ursula" let ursula = wizards;
So… why would you use the
Array.prototype.at() method instead of bracket notation?
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
let gandalf = wizards.at(-1);