The JavaScript array.at() method
The at() method returns the element at a given index, and crucially it accepts negative indices that count from the end. arr.at(-1) is the last element — far nicer than arr[arr.length - 1]. For positive indices it behaves just like bracket notation arr[i].
Overview
at() reads an element by index, with one big convenience over the usual square brackets: it understands negative indices. arr.at(-1) gives you the last element, arr.at(-2) the second-to-last, and so on. That replaces the clunky arr[arr.length - 1] with something readable.
For non-negative indices, at(2) does exactly what arr[2] does. The win is entirely at the back end of the array, where counting from the end is a common need — grabbing the last item of a list, the most recent entry, the final character (it works on strings too).
It returns undefined if the index is out of range, the same as bracket access. Use bracket notation for ordinary forward indexing and at() when you want to count from the end without the length arithmetic.
Syntax
array.at(index)
[10, 20, 30].at(0) // 10
[10, 20, 30].at(-1) // 30 (last)
[10, 20, 30].at(-2) // 20
Parameters
The array.at() method accepts the following parameters.
| Parameter | Description |
|---|---|
index |
The position to read. Negative values count back from the end (-1 is the last element). |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const log = ['boot', 'login', 'click', 'logout'];
document.getElementById('out').textContent =
'first: ' + log.at(0) + '\n' +
'last: ' + log.at(-1) + '\n' +
'prev: ' + log.at(-2); // first: boot / last: logout / prev: click
</script>
Best practices
- Use
arr.at(-1)for the last element instead ofarr[arr.length - 1]. - Stick with bracket notation
arr[i]for ordinary forward indexing. - It returns
undefinedfor an out-of-range index, like bracket access. - It works on strings too —
str.at(-1)is the last character.
Frequently asked questions
How do I get the last element of an array?
arr.at(-1), which counts from the end — cleaner than arr[arr.length - 1].What is the difference between at() and bracket notation?
at() accepts negative indices to count from the end, which arr[-1] does not.Does at() work on strings?
"hello".at(-1) returns "o".What does at() return for an out-of-range index?
undefined, the same as bracket access.