More JavaScript answers

by Danny
Published 2 min read

Use

The short answer

#

Call at(-1) on the array. Negative numbers count back from the end, so -1 is the last item, -2 the second to last, and so on. It returns undefined for an empty array and does not change the original.


_10
const steps = ['plan', 'build', 'ship'];
_10
_10
steps.at(-1); // 'ship'
_10
steps.at(-2); // 'build'

Why it happens

#

Square-bracket indexing in JavaScript does not support negative numbers. steps[-1] does not mean "from the end". It looks up a property literally called '-1', which does not exist, so you get undefined.

The traditional workaround is steps[steps.length - 1], which works but repeats the array name and is awkward for long expressions. The at() method was added to arrays, strings and typed arrays in ES2022 to fix this, and has been supported in all major browsers and Node.js for several years.

How to fix it

#

Use at(-1)

This is the clearest option and works well at the end of a chain.


_10
const latest = orders
_10
.filter((order) => order.status === 'paid')
_10
.at(-1);

It works the same way on strings.


_10
'hello'.at(-1); // 'o'

Use length - 1 when you also need to assign

at() is read-only. To replace the last item, index it with length - 1.


_10
const scores = [10, 20, 30];
_10
scores[scores.length - 1] = 35;
_10
console.log(scores); // [10, 20, 35]

In React state or anywhere you avoid mutation, use with() instead. It returns a copy with one item replaced and also accepts negative indexes.


_10
const updated = scores.with(-1, 35); // scores is unchanged

Use slice(-n) for the last few items

slice with a negative start returns a new array of the last n items.


_10
const messages = ['a', 'b', 'c', 'd', 'e'];
_10
messages.slice(-3); // ['c', 'd', 'e']
_10
messages.slice(-1); // ['e'] (an array, not the item)

Use pop() only when you want to remove it

pop() returns the last item and removes it from the array. That is right for a stack, but surprising if you only meant to read it.


_10
const stack = [1, 2, 3];
_10
const top = stack.pop(); // 3
_10
console.log(stack); // [1, 2]

Use findLast() for the last match

If you want the last item that matches a condition, findLast searches from the end without copying or reversing the array. findLastIndex returns its position.


_10
const lastError = logs.findLast((entry) => entry.level === 'error');

Common pitfalls

#
  • Using array[-1]. It returns undefined rather than throwing, so the bug can go unnoticed. Use at(-1).
  • Forgetting empty arrays. [].at(-1) is undefined. Add a fallback with ?? if you need a default: items.at(-1) ?? null.
  • Using reverse() to get the end. reverse() changes the original array in place. If you need a reversed copy, use toReversed().
  • Expecting slice(-1) to return the item. It returns a one-item array. Add [0], or just use at(-1).
  • Array-like objects. A NodeList from querySelectorAll, an HTMLCollection and the arguments object are not arrays and have no at method. Convert with Array.from(list).at(-1).
  • TypeScript types. at(-1) is typed as T | undefined, which is accurate. Handle the undefined case rather than asserting it away.
#

Was this resource helpful?