Array.prototype.at
Returns the element at an index; negative indexes are allowed.
Available since: ES2022
Syntax
array.at(index)Parameters
| Parameter | Type | Description |
|---|---|---|
| index | number | The position of the element, counting from zero. A negative number counts from the end. |
Return value
anyThe element, or undefined if there is no such position.
Examples
The last element:
const colors = ['red', 'green', 'blue'];
console.log(colors.at(-1));Output:
bluePositive indexes work like square brackets:
const colors = ['red', 'green', 'blue'];
console.log(colors.at(0), colors[0]);
console.log(colors.at(-2));
console.log(colors.at(10));Output:
red red
green
undefinedNotes
colors[-1] does not work as in Python — it reads a property named -1 and gives undefined. To count from the end you need at().
See also
- Array.prototype.length — The number of elements in an array.
- Array.prototype.slice — Returns part of an array.
- String.prototype.at — Returns the character at a position; negative indexes are allowed.
Related recipes
In the tutorial
- Arrays — What an array is in JavaScript: creating one, indexes, length, changing elements and nested arrays.