Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

Array.prototype.at()

Reference for JavaScript Array.prototype.at(): read an element by index with support for negative indexes, such as the last item, and how it differs from brackets.

The at() method returns the element at a given index. Unlike bracket notation, it accepts negative integers, which count back from the end: -1 is the last element, -2 the one before it, and so on.

It saves you from writing array[array.length - 1], which is the main reason it was added. The same method exists on strings and typed arrays.

JavaScript
const letters = ["a", "b", "c"];
letters.at(-1); // "c"

Try it

JS Counting from the end

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS at() versus brackets

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
array.at(index)
Name Description
index Zero-based position. It is converted to an integer (the fraction is cut off). A negative value counts from the end.

Return value: the element at that position, or undefined if the position is outside the array.

Exceptions: none. It never throws for an out-of-range index.

Usage notes

  • Read only. at() does not mutate the array and cannot be used on the left of an assignment: arr.at(-1) = x is a syntax error. Use arr[arr.length - 1] = x to assign.
  • array[-1] is not the same. In JavaScript, -1 in brackets is just a property name, so you get undefined unless such a property exists.
  • Conversion: non-numbers are converted, NaN and a missing argument become 0, and fractions are truncated toward zero, so at(1.9) is index 1.
  • Out of range returns undefined, even for very negative indexes.
  • Chaining works well on call results, because you do not need a temporary variable to know the length: getItems().at(-1).
  • Holes: reading a hole returns undefined, like brackets.
  • Generic: it can be called on array-likes with Array.prototype.at.call(obj, -1).
  • Related finders: findLast() returns the last element that passes a test, while at(-1) simply returns the last element.

Browser support

Array.prototype.at() is available in all current browsers. It is newer than the classic array methods, so check a compatibility table if you must support very old browsers.