Array.prototype.at() - A better way to access JS array elements

js

TC39 introduced a handful of non-mutating array methods in recent years. This post is a first in a series illustrating these new methods.Array.prototype.at() by itself isn't a super interesting demo but in later posts I'll demo the others like with() and toSplice() and how to use them together.

Introduced around 2021 the at() method is supported in all modern browsers and Node.js 16+.

Basic use


To use just simply pass the index of the element you want to access.

const snacks = ["ice cream", "tea", "coffee", "cookies"];
console.log(snacks.at(0)); // "ice cream"
console.log(snacks.at(2)); // "coffee"
// negative indexes count from the end of the array"
console.log(snacks.at(-2)); // "coffee"

If the element doesn't exist, at() returns undefined just like accessing an array element with bracket notation.

const snacks = ["ice cream", "tea", "coffee", "cookies"];
console.log(snacks.at(5)); // undefined

Using it to access the last element of an array


The most common use case for at() is to access the last element of an array. Before at() you would have to use the length of the array - 1:

const snacks = ["ice cream", "tea", "coffee", "cookies"];
console.log(snacks[snacks.length - 1]); // "cookies"

With at() you can do this much more succinctly:

const snacks = ["ice cream", "tea", "coffee", "cookies"];
console.log(snacks.at(-1)); // "cookies"

Maybe not such a big deal in a basic use case but when using it chained with other methods or not just for accessing the last element it's much more readable.

Using it chained with other methods


Here's an example of using it chained with map() to get the last time a user ate ice cream:

const snackLog = [
  { snack: "ice cream", date: "2022-01-01" },
  { snack: "tea", date: "2022-01-02" },
  { snack: "coffee", date: "2021-01-03" },
  { snack: "ice cream", date: "2022-05-10" },
  { snack: "cookies", date: "2022-01-04" },
  { snack: "ice cream", date: "2022-01-05" },
];
 
const lastIceCream = snackLog
  .filter((entry) => entry.snack === "ice cream")
  .toSorted((a, b) => new Date(a.date) - new Date(b.date))
  .at(-1);
 
console.log(lastIceCream.date); // "2022-05-10"

at() on MDN
TC39 spec