JavaScript Array at()
Examples
Get the third element of fruits:
let fruit = fruits.at(2);
Get the third element of fruits:
let fruit = fruits[2];
More examples below.
Description
The at()
method returns an indexed element from an array.
The at()
method returns the same as []
.
The at()
method is supported in all modern browsers since March 2022:
Note
Many languages allows negative bracket indexing
like [-1] to access elements from the end of an
object / array / string.
This is not possible in JavaScript, because [] is used for accessing both arrays and objects. obj[-1] refers to the value of key -1, not to the last property of the object.
The at()
method was introduced in ES2022 to solve this problem.
Syntax
Parameters
The index (position) of the array element to be returned.
Default is 0.
-1 returns the last element.
Return Value
Array Tutorials:
Browser Support
JavaScript Array at()
is supported in all browsers since March 2022:
Chrome 92 | Edge 92 | Firefox 90 | Safari 15.4 | Opera 78 |
Apr 2021 | Jul 2021 | Jul 2021 | Mar 2022 | Aug 2021 |
More Examples
Get the first element of fruits:
let fruit = fruits.at();
Get the last element of fruits:
let fruit = fruits.at(-1);