JS: Array.prototype.at

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2022)

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

Works with JS: Array-Like Object.

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

const xx = [1, 2, 3, 4, 5];
console.log(xx.at(-1) === 5);
// example of Array.prototype.at on array-like object
let xx = { 0: "a", 1: "b", length: 2 };
const yy = Reflect.apply(Array.prototype.at, xx, [0]);
console.log(yy === "a");

Js, Array Get Set an Element by Index