JavaScriptArrays
Array. prototype. at()
Returns the element at the given index, which can also be counted from the end.
- Returns
- The element at the given index, or
undefined. - Changes the original
- No
Example
#JavaScript
const scores = [55, 70, 88, 92]
console.log(scores.at(0))
console.log(scores.at(-1))
console.log(scores.at(-2))
console.log(scores.at(10))Console
55
92
88
undefined
Definition and usage
#The at() method returns the array element at the given index. Its main advantage is support for negative indexes: at(-1) returns the last element, at(-2) the second-to-last.
Before this method existed, reading the last element meant writing array[array.length - 1], which is longer and easier to get wrong.
For an out-of-range index, at() returns undefined. The method also works on strings: "CodeWorlds".at(-1) is "s".
Syntax
#Syntax
array.at(index)Parameters
#index
integer
The element’s index. Negative values count from the end.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- For the last element, use
at(-1). The code is shorter and clearer thanlength - 1. at()doesn’t change the array. To remove the last element, usepop().
Related entries
#- Array.prototype.lengthThe number of elements in the array, which you can also change.
- Array.prototype.pop()Removes the last element of an array and returns it.
- Array.prototype.findLast()Returns the last element that matches a condition, searching the array from the end.
- String.prototype.at()Returns the character at the given index. Negative indexes count from the end, so at(-1) is the last character.
- Array.prototype.with()Returns a copy of the array in which the element at the given index has a new value.
Spotted a mistake or missing an example? Write to us.