Access from the end
Read the most recent item without manually subtracting from length.
JavaScript · Function
Array.prototype.at() returns the element at a given integer index and supports negative indexes that count from the end. It returns undefined when the index is outside the array's bounds.
Call at(index) on an array to read one element. The index is converted to an integer; non-negative values count from the beginning, while negative values are added to the array length so they count backward from the end. An index outside the array produces undefined.
at(index)| Name | Type | Description |
|---|---|---|
index | integer | A zero-based index, converted to an integer. Negative values count from the end of the array. |
The element at the selected index, or undefined when the index is outside the array's bounds.
const colors = ["red", "green", "blue"];
console.log(colors.at(0)); // "red"
console.log(colors.at(-1)); // "blue"
console.log(colors.at(99)); // undefinedUse a non-negative index for ordinary access and a negative index to count from the end.
Read the most recent item without manually subtracting from length.
Use a concise, readable alternative to array[index] for ordinary element lookup.
Read values from objects that expose length and integer-keyed properties.
at(index) returns the element at a zero-based index. Negative indexes count backward from the array's end, so at(-1) returns the final element; an out-of-range index returns undefined.
Follow-up: How does at() differ from bracket notation for negative indexes? Bracket notation treats -1 as the string property "-1", whereas at(-1) performs relative indexing.
For a non-negative integer, at(index) is equivalent to array[index]. Its distinctive feature is that a negative index is translated relative to the array length.
Follow-up: What happens for a fractional index? The argument is converted to an integer before the element lookup.
The method is generic: it needs a this value with a length property and integer-keyed properties. Therefore, it can read from suitable array-like objects, not only actual arrays.
Follow-up: Can it be used on a typed array? TypedArray.prototype.at() has the same algorithm, but the typed-array method itself is not generic.
Array.prototype.with()Array.prototype.slice()TypedArray.prototype.at()