Today, I wanted to quickly share the
Array.prototype.at() method: how it works, and when you might use it.
Let’s dig in!
Getting an item from an array by its index
Let’s imagine you have an array of wizards, like this.
let wizards = [ 'Merlin', 'Gandalf', 'Ursula', 'Radagast', 'Morgana' ];
Using bracket notation, you can get an item by its index (remember, array indexes start at
// returns "Ursula" let ursula = wizards; // returns "Morgana" let morgana = wizards;
Doing the same thing with
Array.prototype.at() method does the same thing. Call it on the array, and pass in the index you want. It returns the matching item.
// returns "Ursula" let ursula = wizards.at(2); // returns "Morgana" let morgana = wizards.at(4);
So if it does the same thing, what’s the point? I’ve avoided looking at this method for a long time because it always seemed kind of pointless.
But recently, my friend Steve Griffith pointed out a great use for this method: grabbing items from the end of an array.
Getting items from the end of an array
To get an item from the end of an array with bracket notation, you need to get the length of the array, subtract the number back from the end you want to go, and pass that in.
// returns "Radagast" let secondToLastWizard = wizards[wizards.length - 2];
Array.prototype.at() method, you just pass in the index as a negative integer.
// returns "Radagast" let secondToLastWizard = wizards.at(-2);
If you’re a visual learner, Steve does a great job of explaining this in his video.