inspection

Array.prototype.at

Returns the element at the given integer index, supporting negative values that count from the end (ES2022). Reach for it as the clean replacement for `arr[arr.length - 1]`.

arr.at(index)

Parameters

Parameter Purpose
index Integer index; negative values count from the end (-1 is last)
return value The element at that index, or undefined if out of range

Examples

console.log(['a','b','c'].at(0));

Logs: 'a'

console.log(['a','b','c'].at(-1));

Logs: 'c'

console.log(['a','b','c'].at(-2));

Logs: 'b'

console.log(['a','b','c'].at(99));

Logs: undefined

Gotcha

Requires ES2022 (Node 16.6+, all modern browsers). Bracket notation `arr[-1]` returns undefined — always use `.at(-1)` for the last element.

Related methods

← All JS array methods · TypeScript vs JavaScript