Array at()
Array.prototype.at() returns the item at a given index and accepts negative numbers to count from the end. It makes tail access clearer than repeating array.length calculations.
Overview
Array.prototype.at() returns the item at a given index and accepts negative numbers to count from the end. It makes tail access clearer than repeating array.length calculations.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 92 | 92 | 90 | 15.4 | 92 | 15.4 | |
| Built-in object | ||||||
| The at() method of TypedArray instances takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the typed array. This method has the same algorithm as Array.prototype.at(). | 92 | 92 | 90 | 15.4 | 92 | 15.4 |
Syntax
const arr = ['a', 'b', 'c', 'd', 'e'];
arr.at(0); // 'a'
arr.at(-1); // 'e' (last element)
arr.at(-2); // 'd' (second-to-last element)
// Comparison with the traditional syntax
arr[arr.length - 1]; // 'e' ← verbose
arr.at(-1); // 'e' ← concise Live demo
Use cases
Accessing the last item
Use at(-1) for recent logs, latest messages, or the current step without spelling out length arithmetic.
Looking near the end
Negative indexes keep code readable when you need the previous or second-to-last item in a sequence.
Cautions
- Out-of-range access still returns undefined, so guard if a missing value would break later logic.
- If you need the index for further array operations, a direct index variable may still be clearer than repeated at() calls.
Accessibility
- When the last item controls what users hear or see, make sure the visible order matches the data order you are reading from.
Related links
Powered by web-features