JavaScript Array at()

Definition and Usage

at() method returns the element at the specified index position in the array.

at() The method is similar to [] has the same effect.

Since March 2022,at() The method is supported in all modern browsers.

Note

Many programming languages allow the use of negative indices (such as [-1]) to access the end elements of objects/arrays/strings.

In JavaScript, this is not possible because [] Used to access arrays and objects. obj[-1] refers to the value of the key -1, not the last property of the object.

at() The method was introduced in ES2022 to solve this problem.

Example

Example 1

Get the third element of the fruits array:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.at(2);

Try It Yourself

Example 2

Use [] to get the third element of the fruits array:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[2];

Try It Yourself

Example 3

Get the first element of the fruits array:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.at();

Try It Yourself

Example 4

Get the last element of the fruits array:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.at(-1);

Try It Yourself

Syntax

array.at(index)

Parameter

Parameter Description
index

Optional. The index (position) of the array element to return.

Default value is 0. -1 returns the last element.

Return Value

Type Description
the element at the given position (index) in the array.

Browser Support

Since March 2022, JavaScript arrays at() The method is supported in all browsers:

Chrome Edge Firefox Safari Opera
Chrome 92 Edge 92 Firefox 90 Safari 15.4 Opera 78
April 2021 July 2021 July 2021 March 2022 August 2021