The .at() method, introduced in ES2022, is a clean and modern way to access elements in an array. While it works similarly to the traditional bracket notation array[index], its superpower is how it handles negative indexing.
1. Basic Syntax
The .at() method takes an integer value and returns the item at that index.
JavaScript
const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits.at(0)); // "Apple"
console.log(fruits.at(1)); // "Banana"
2. Why Use .at() Instead of []?
A. Readability
When working with the end of an array, arr.at(-1) is much shorter and easier to read than arr[arr.length - 1]. This is especially helpful if the array name is long (e.g., userProfile.metadata.loginHistory.at(-1)).
B. Method Chaining
Since .at() is a method, it fits perfectly into chains of other array methods like .sort() or .filter().
const topScore = [45, 80, 12, 95, 33]
.sort((a, b) => a - b)
.at(-1); // Gets the highest value after sorting
console.log(topScore); // 95
C. String Support
The .at() method also works on Strings, providing the same negative indexing benefits.
JavaScript
const message = "JavaScript";
console.log(message.at(-1)); // "t"
3. Key Characteristics
Works on Strings Too
Since strings are “array-like” in JavaScript, you can use .at() to grab characters from the end of a string without calculating lengths.
const message = "Hello World";
console.log(message.at(-1)); // 'd'
Out-of-Bounds Handling
If the index you provide doesn’t exist (e.g., the array has 3 items and you ask for .at(5)), it returns undefined, just like square brackets.
const list = [1, 2, 3];
console.log(list.at(10)); // undefined
4. The Power of Negative Indexing
Before .at(), if you wanted to get the last item of an array, you had to use the .length property. With .at(), you simply use -1.
const colors = ['Red', 'Green', 'Blue', 'Gold'];
// The old, clunky way
const lastOld = colors[colors.length - 1];
// The modern .at() way
const lastNew = colors.at(-1);
const secondToLast = colors.at(-2);
console.log(lastNew); // 'Gold'
console.log(secondToLast); // 'Blue'
