JS: Array.prototype.at

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2022)

xArray.at(n)
  • return the element at index n
  • n can be negative, meaning counting from right.

🟢 TIP: similar to xArray[n], but allow negative index.

console.assert([1, 2, 3, 4, 5].at(-1) === 5);

Edge case. Array-Like object.

Works with Array-Like Object.

// example of Array.prototype.at on array-like object
console.assert(
 (Reflect.apply(
  Array.prototype.at,
  { 0: "a", 1: "b", length: 2 },
  [0],
 )) === "a",
);

Js, Array Get Set an Element by Index