JavaScript Reference ยท Array
Array.prototype.at()
Reference for JavaScript Array.prototype.at(): read an element by index with support for negative indexes, such as the last item, and how it differs from brackets.
The at() method returns the element at a given index. Unlike bracket notation, it accepts negative integers, which count back from the end: -1 is the last element, -2 the one before it, and so on.
It saves you from writing array[array.length - 1], which is the main reason it was added. The same method exists on strings and typed arrays.
const letters = ["a", "b", "c"]; letters.at(-1); // "c"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.at(index)
| Name | Description |
|---|---|
index |
Zero-based position. It is converted to an integer (the fraction is cut off). A negative value counts from the end. |
Return value: the element at that position, or undefined if the position is outside the array.
Exceptions: none. It never throws for an out-of-range index.
Usage notes
- Read only.
at()does not mutate the array and cannot be used on the left of an assignment:arr.at(-1) = xis a syntax error. Usearr[arr.length - 1] = xto assign. array[-1]is not the same. In JavaScript,-1in brackets is just a property name, so you getundefinedunless such a property exists.- Conversion: non-numbers are converted,
NaNand a missing argument become0, and fractions are truncated toward zero, soat(1.9)is index1. - Out of range returns
undefined, even for very negative indexes. - Chaining works well on call results, because you do not need a temporary variable to know the length:
getItems().at(-1). - Holes: reading a hole returns
undefined, like brackets. - Generic: it can be called on array-likes with
Array.prototype.at.call(obj, -1). - Related finders:
findLast()returns the last element that passes a test, whileat(-1)simply returns the last element.
Browser support
Array.prototype.at() is available in all current browsers. It is newer than the classic array methods, so check a compatibility table if you must support very old browsers.