Array at(): negative indexing from the end (ES2022)
What you’ll learn
Section titled “What you’ll learn”- How
at()reads an element by position, with negative numbers counting from the end. - Why
arr[-1]cannot mean “last element” in JavaScript. - The coercion edge cases that make
at('last')return the first element. - How
at()behaves on strings, typed arrays and array-likes, and how TypeScript types it.
Summary
Section titled “Summary”TL;DR: array.at(i) returns the element at index i. A negative i counts back from the end: at(-1) is the last element, at(-2) the one before it. An out-of-range index returns undefined.
It was added in ECMAScript 2022 on Array, String and typed arrays, and is supported by all current browsers and Node.js 16.6 and later.
The problem it solves
Section titled “The problem it solves”Reading the last element meant naming the array twice, arr[arr.length - 1], which needs a temporary variable when the array comes from an expression. The alternative, arr.slice(-1)[0], allocates a throwaway array.
Python-style arr[-1] cannot be added. Square brackets are property access on any object, so arr[-1] already means “the property named '-1'”, and changing that would break existing code. A method was the only option. The proposal first named it item(), but that broke sites using the YUI libraries, which detected DOM collections by checking for an item property, so it was renamed at().
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. The outputs shown were produced with Node.js 22.23. The sample uses tracking events from the invented OrdersPortal app.
const trackingEvents = ['label created', 'picked up', 'in transit', 'out for delivery'];
// Before ES2022: repeat the array name, or allocate a throwaway array.console.log(trackingEvents[trackingEvents.length - 1]); // out for deliveryconsole.log(trackingEvents.slice(-1)[0]); // out for delivery
// Bracket notation does not count from the end: -1 is just a property key.console.log(trackingEvents[-1]); // undefined
// After: negative indexes count back from the end.console.log(trackingEvents.at(-1)); // out for deliveryconsole.log(trackingEvents.at(-2)); // in transitconsole.log(trackingEvents.at(0)); // label createdconsole.log(trackingEvents.at(4), trackingEvents.at(-5)); // undefined undefined
// Works on any expression, with no temporary variable.console.log('invoice-2026-11.final.pdf'.split('.').at(-1)); // pdfHow it works
Section titled “How it works”The specification algorithm is short:
- Convert the argument with
ToIntegerOrInfinity: truncate toward zero, and turnNaN(includingundefinedand non-numeric strings) into0. - If the result is negative, add
length(steps 1 and 2 are the spec’sToAbsoluteIndexoperation). - If the index is still below
0or at leastlength, returnundefined; otherwise return the element.
That makes at() a read-only, bounds-checked lookup. The coercion step is where the surprises are:
const a = ['x', 'y', 'z'];
// The index is converted with ToIntegerOrInfinity: truncated toward zero, NaN becomes 0.console.log(a.at(1.9), a.at(-1.9)); // y zconsole.log(a.at('1')); // yconsole.log(a.at(), a.at(NaN), a.at('last')); // x x x <- a typo silently returns the first elementconsole.log(a.at(Infinity), a.at(-Infinity)); // undefined undefined
// Strings: at() indexes UTF-16 code units, so it can split an emoji.const label = 'Gift 🎁';console.log(label.at(-1) === '\uDF81', label.at(-1).length); // true 1console.log([...label].at(-1)); // 🎁 (spread iterates by code point)
// Typed arrays and array-likes.console.log(new Float64Array([1.5, 2.5]).at(-1)); // 2.5console.log(Array.prototype.at.call({ length: 2, 0: 'first', 1: 'second' }, -1)); // second
// at() only reads. To "replace the last element" without mutating, use with() (ES2023).console.log(a.with(-1, 'Z'), a); // [ 'x', 'y', 'Z' ] [ 'x', 'y', 'z' ]Like find(), at() reads holes as undefined and is generic. DOM collections such as NodeList and HTMLCollection do not have at(); call Array.prototype.at.call(list, -1) or convert with Array.from().
TypeScript
Section titled “TypeScript”at() is declared in lib.es2022.array.d.ts as returning T | undefined, so strict mode makes you handle the empty case. Plain indexing returns T unless you enable noUncheckedIndexedAccess:
// Fragment: TypeScript 6.0.3, --strict --target es2022const totals: number[] = [];const viaIndex = totals[totals.length - 1]; // number, but undefined at runtimeconst viaAt = totals.at(-1); // number | undefinedconsole.log(viaIndex.toFixed(2)); // compiles, then throws TypeError at runtime// viaAt.toFixed(2); // error TS18048: 'viaAt' is possibly 'undefined'.console.log(viaAt?.toFixed(2) ?? 'no orders');Realistic example
Section titled “Realistic example”The OrdersPortal tracking widget shows the latest scan and how long it took since the previous one. at(-1) and at(-2) read naturally, and both return undefined for short arrays, so the empty and single-scan cases fall out of ordinary checks.
// shipment-summary.mjs - OrdersPortal tracking widget.const scans = [ { location: 'North hub', at: '2026-11-03T08:10Z' }, { location: 'City depot', at: '2026-11-03T15:45Z' }, { location: 'Delivery van 12', at: '2026-11-04T07:30Z' },];
export function summarize(scans) { const latest = scans.at(-1); const previous = scans.at(-2); if (!latest) return 'No scans yet'; const hours = previous ? (Date.parse(latest.at) - Date.parse(previous.at)) / 3_600_000 : 0; return `${latest.location} (${previous ? `${hours.toFixed(1)} h after ${previous.location}` : 'first scan'})`;}
console.log(summarize(scans));console.log(summarize(scans.slice(0, 1)));console.log(summarize([]));Output:
Delivery van 12 (15.8 h after City depot)North hub (first scan)No scans yetCommon mistakes
Section titled “Common mistakes”- Expecting
arr[-1]to work. It reads a property named'-1'and returnsundefined(or, worse, a value someone stored under that key). - Passing a non-numeric value.
at('last'),at(undefined)andat(NaN)all return the first element, notundefined. Validate computed indexes. - Trying to assign through it.
arr.at(-1) = xis never valid: the specification makes it an earlySyntaxErrorin strict code, and Node.js 22 throwsReferenceError: Invalid left-hand side in assignmentwhen the line runs. Usearr[arr.length - 1] = xto mutate, orwith(-1, x)for a copy. - Using it for characters beyond the BMP.
string.at(-1)returns one UTF-16 code unit, which can be half of an emoji. Use[...string].at(-1)for code points, orIntl.Segmenterfor user-perceived characters. - Calling it on a
NodeList. DOM collections lackat(); borrow the array method or convert first.
When to use it and when not to
Section titled “When to use it and when not to”Use at() for negative or relative indexes, and when the array is the result of an expression. For a plain non-negative index, arr[i] is equally clear and works everywhere. To search by condition from the end, use findLast(); at() only reads by position.
| You want | Use |
|---|---|
| The last (or n-th from last) element | at(-1), at(-n) |
| The element at a known non-negative index | arr[i] |
| The last element that matches a condition | findLast() |
| A copy with the last element replaced | with(-1, value) |
| The last n elements | slice(-n) |
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, Array.prototype.at() and String.prototype.at() are supported in Chrome 92, Edge 92, Firefox 90, Safari 15.4 (including iOS), Node.js 16.6, Deno 1.12 and Bun 1.0; typed-array at() has the same browser and Node.js versions. Internet Explorer never supported it. TypeScript’s types are in lib.es2022.array.d.ts and lib.es2022.string.d.ts; add es2022 or later to lib if a project pins an older one. core-js polyfills all three.
Interview questions
Section titled “Interview questions”1. Why can’t JavaScript support arr[-1] for the last element, as Python does?
Bracket notation is generic property access: arr[-1] looks up the string key '-1', which any object, including an array, can legally have. Redefining it would break existing code, so negative indexing arrived as a method, at().
2. What does ['a', 'b'].at('last') return?
'a'. The argument is converted with ToIntegerOrInfinity; 'last' becomes NaN, which becomes 0. The same happens with at() and at(undefined).
3. Senior scenario: a team wants a lint rule that replaces every arr[arr.length - 1] with arr.at(-1). What do you check before approving?
The runtime floor: at() needs Safari 15.4 and Node.js 16.6, so older targets need a polyfill. Types change from T to T | undefined, which surfaces real empty-array bugs but also causes compile errors to fix. Assignments such as arr[arr.length - 1] = x cannot be converted. And for strings, both forms index code units, so the rewrite is safe but does not fix emoji handling.
Key takeaways
Section titled “Key takeaways”at(i)(ES2022) reads an element by index; negative values count from the end, and out-of-range returnsundefined.arr[-1]is a property lookup, not negative indexing.- Non-numeric arguments coerce to
0, so a bad index silently returns the first element. - It exists on arrays, strings (UTF-16 code units) and typed arrays, is read-only, and TypeScript types it as
T | undefined.
Related pages
Section titled “Related pages”- Array with(): replace an element by relative index without mutating.
- Array findLast() and findLastIndex(): search from the end by condition.
- Array find() and findIndex(): search from the start.
- Unicode in JavaScript: code units, code points and why
at()can split an emoji. - Optional chaining: handling the
undefinedresult. - JavaScript arrays and strings
Official references
Section titled “Official references”- ECMAScript Language Specification:
Array.prototype.at,String.prototype.atand%TypedArray%.prototype.at(current draft; first published in ECMAScript 2022) - ECMAScript 2022 Language Specification:
Array.prototype.at - TC39 proposal: Relative indexing method (
.at()) - MDN: Array.prototype.at()
- MDN: String.prototype.at()
- TypeScript 6.0.3:
lib.es2022.array.d.ts