David East, but the top half of the face

David East

Web Developer / Designer

JavaScript [].at() is amazing and you should use it

Oct 10, 2022

Hey there! Do you want to hear my incredibly awesome voice read you this article?

The .at() method for arrays in JavaScript is a joy to use with a few tricks as well.

This is where it’s .at()

Working with array indexes in JavaScript has always been… and adventure. If you want a specific part of the array, you need to either do some math with the length or use .slice()… or is it .splice()?

But now it’s okay. We have .at(). This method is on the Array prototype and it’s a joy to use. It takes a single argument: the index of the value you want to retrieve.

const items = ['Apples', 'Oranges', 'Pears', 'Bears'];

// You can use .slice() to the third item in the array
const thirdItemSlice = items.slice(2, 3)[0];

// Or you can use .splice() to the third item in the array
const thirdItemSplice = items.splice(2, 1)[0];

// You can use length to get the third item in the array
const thirdItemLength = items[items.length - 2];

// Or you can use .at() to get the third item in the array
const thirdItemAt = items.at(2);

Look .at() that. It’s so easy. Another amazing aspect of .at() is that the index can be negative.

// davidea.st/articles/javascript-at-array
const currentPath = location.pathname;
// 'javascript-at-array'
const lastPath = currentPath.split('/').at(-1);

The negative number shifts the index from the end length. Basically, you can work with the length without having to actually know the length. We live in the future.