Array.prototype.at()
Exists for one reason: bracket notation cannot do negative indices. arr[-1] looks up a PROPERTY named "-1" and quietly gives undefined.
Demo
Positive indices behave exactly like bracket notation. Negative indices are the point: -1 is the last element, -2 the one before it, and so on. An index outside the array in either direction gives undefined rather than throwing, which is the same behaviour bracket notation has — so at() changes what you can express, not how failure is reported.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| index | number | yes | Position to read. Negative counts from the end, so -1 is the last element. A fractional index is truncated toward zero. |
Return value
any — The element at the index, counting from the end when the index is negative. undefined when the index is out of range.
Common patterns
const last = items.at(-1);
const secondLast = items.at(-2);
const lastChar = 'hello'.at(-1);
Examples
Pitfalls
[1, 2, 3][-1]
[1, 2, 3].at(-1)
items.at(99).name
items.at(99)?.name
items.at(-1)
items[items.length - 1]
When to use
- Reading the last or second-to-last element
- Any index computed relative to the end
- Replacing the arr[arr.length - 1] idiom for readability
- Plain forward indexing → bracket notation is shorter
- Runtimes older than ES2022 → arr[arr.length - 1]
- You want to WRITE to the position → at() is read-only
Notes
FAQ
Because arrays are objects and bracket notation with -1 looks up a property literally named "-1". No such property exists, so you get undefined rather than the last element. at() interprets the number as an index and counts from the end.
[1, 2, 3][-1] // undefined [1, 2, 3].at(-1) // 3