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
On this page

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 than length - 1.
  • at() doesn’t change the array. To remove the last element, use pop().

Related entries

#

Spotted a mistake or missing an example? Write to us.