Hiprup

What is Array.at() method?

Array.at(index) reads an element by index, with support for negative indices that count from the end.

  • Negative index — arr.at(-1) returns the last element, cleaner than arr[arr.length - 1].

  • Works on strings too — and other indexable built-ins.

In short: a small but readable improvement for grabbing items from the end.

const arr = ['a', 'b', 'c', 'd', 'e'];

// Positive index (same as bracket notation)
console.log(arr.at(0));   // 'a'
console.log(arr.at(2));   // 'c'

// Negative index (counts from end)
console.log(arr.at(-1));  // 'e' (last)
console.log(arr.at(-2));  // 'd' (second to last)

// Before at() — verbose
console.log(arr[arr.length - 1]); // 'e'

// Works on strings
console.log('hello'.at(-1)); // 'o'

// Chaining (cannot do with bracket notation)
const lastItem = getItems().at(-1); // Clean!
// vs: const items = getItems(); const lastItem = items[items.length - 1]; // Verbose

at(0) = arr[0]. at(-1) = arr[arr.length - 1] (last element). at(-2) = second from end. The main advantage: negative indexing is built-in, cleaner than arr.length - 1.

Works on strings too. Chainable: getItems().at(-1) is not possible with bracket notation.

at(-1) for the last element is the key use case — replaces arr[arr.length - 1]. Works on arrays and strings.

ES2022 — know the year. The chaining advantage (getItems().at(-1)) is a practical bonus.

What is Array.at() method? | Hiprup