Read from the end with Array.at
Use .at(-1) to read an array’s last item, with undefined as the result when the array is empty.
You need the last item of an array, so you write arr[arr.length - 1]. It works. It also makes you name the array twice, which gets awkward when the array is the result of a function call.
const getPath = () => '/docs/guides/intro.md'.split('/')
// before: a temporary variable, just to read the end
const parts = getPath()
console.log(parts[parts.length - 1]) // intro.md
// after
console.log(getPath().at(-1)) // intro.mdBoth lines print intro.md, and the second one needs no variable.
Count from the end
at() takes an integer index. A negative index counts back from the end: -1 is the last item, -2 the one before it.
MDN defines the lookup as index + array.length when index is negative, so at(-1) reads the same item as arr[arr.length - 1]. On a five item array, at(-1) looks up index 4 and at(-5) looks up index 0.
I write .at(-1) wherever I used to write the length form. That includes chains like str.split('/').at(-1) for a file name.
Out of range gives undefined
Square brackets do not understand negative numbers. arr[-1] looks up a property named "-1", finds nothing, and returns undefined with no error. If you swap arr[arr.length - 1] for arr[-1] by mistake, nothing warns you.
const arr = [5, 12, 8, 130, 44]
console.log(arr.at(-1)) // 44
console.log(arr.at(-2)) // 130
console.log(arr[-1]) // undefined
console.log(arr.at(-6)) // undefined, only five items
console.log([].at(-1)) // undefined, empty arrayat() returns undefined for any index outside the array, which includes every index on an empty array. It does not throw for an out-of-range index. The failure shows up later, when you read a property of the result.
const users = []
console.log(users.at(-1)?.name) // undefined
console.log(users.at(-1).name) // TypeError: Cannot read properties of undefined (reading 'name')Put ?. after at(-1) when the array can be empty.
Reading only
at() returns a value, not a reference to a slot, so you cannot assign through it. arr.at(-1) = 99 is an invalid assignment target.
To replace the last item, check that the array has an item, then write arr[arr.length - 1] = 99. On an empty array, that assignment creates a property called "-1".
The index is converted to an integer first, so arr.at(1.9) reads index 1 and arr.at('2') reads index 2. I have not found a reason to rely on that. Pass integers.
MDN lists at() as available across browsers since March 2022. If you still ship to browsers older than that, keep the length form in that code.