Sub topic 2
Reading from the End with at()
This chapter assumes you already know how to create arrays, read elements with square brackets, and use the length property. It also assumes you are comfortable with functions and running code in Node.js or a browser console.
Reading the first element of an array is easy: arr[0]. Reading the last one has always been clumsier. You had to write arr[arr.length - 1], which repeats the array's name and leaves room for off-by-one mistakes. The at() method, added in ES2022, accepts negative indexes that count back from the end. This chapter covers how at() resolves an index, where it behaves differently from bracket access, and the edge cases that surprise people.
The working model
at(index) returns the element at index. A non-negative index works like bracket access. A negative index counts from the end, so -1 is the last element, -2 the one before it, and so on. If the resolved position falls outside the array, at() returns undefined and does not throw.
const queue = ['first', 'second', 'third', 'fourth'];
console.log(queue.at(0)); // 'first'
console.log(queue.at(2)); // 'third'
console.log(queue.at(-1)); // 'fourth'
console.log(queue.at(-2)); // 'third'
console.log(queue.at(10)); // undefined
console.log(queue.at(-10)); // undefinedHere is the rule in one sentence: when the index is negative, at() adds length to it and then reads that position. For a four-element array, at(-1) reads position 4 + (-1) = 3.
Why negative bracket indexes don't work
Some languages, such as Python, let arr[-1] mean "last element". JavaScript does not. Square brackets on an array are ordinary property access. arr[-1] looks up a property named "-1", and arrays don't have one, so you get undefined.
Writing to a negative bracket index is worse than reading from one. It doesn't fail. It quietly creates a regular property that is not part of the array's elements:
const scores = [70, 85, 92];
console.log(scores[-1]); // undefined, not 92
scores[-1] = 100; // creates a property named "-1"
console.log(scores.length); // 3 (unchanged)
console.log(scores); // [ 70, 85, 92, '-1': 100 ] in Node.js
console.log(scores.at(-1)); // 92 (at() ignores the stray property)
console.log(Object.keys(scores)); // [ '0', '1', '2', '-1' ]Array methods such as map, forEach, and for...of skip that stray property, because they only visit index positions from 0 to length - 1. Object.keys and for...in still show it, so the bug tends to come up somewhere far from the line that caused it.
Comparing ways to read the last element
| Expression | Last element of `[1, 2, 3]` | Empty array `[]` | Notes |
|---|---|---|---|
| `arr[arr.length - 1]` | `3` | `undefined` | Works everywhere and repeats the array name |
| `arr.at(-1)` | `3` | `undefined` | Clear and short; needs ES2022 |
| `arr.slice(-1)[0]` | `3` | `undefined` | Allocates a new array just to read one value |
| `arr[-1]` | `undefined` | `undefined` | Wrong: reads a property named `"-1"` |
| `arr.pop()` | `3` | `undefined` | Wrong for reading: it removes the element |
The difference between at(-1) and arr[arr.length - 1] matters most when the array comes from an expression rather than a variable. With brackets you need a temporary variable. With at() you can read the result directly:
const words = 'the quick brown fox'.split(' ');
// Without at(): needs a variable to reference twice
const parts = 'the quick brown fox'.split(' ');
console.log(parts[parts.length - 1]); // 'fox'
// With at(): reads straight off the expression
console.log('the quick brown fox'.split(' ').at(-1)); // 'fox'
console.log(words.filter(w => w.length > 3).at(-1)); // 'brown'How the argument is converted
at() converts its argument to an integer before using it. The conversion truncates toward zero, and NaN or a missing argument becomes 0. Because of this, some mistakes return a value instead of undefined:
const items = ['a', 'b', 'c'];
console.log(items.at(1.9)); // 'b' (1.9 truncates to 1)
console.log(items.at(-1.9)); // 'c' (-1.9 truncates to -1)
console.log(items.at('2')); // 'c' (string converted to 2)
console.log(items.at()); // 'a' (undefined becomes 0)
console.log(items.at(NaN)); // 'a' (NaN becomes 0)
console.log(items.at('x')); // 'a' ('x' is NaN, so 0)
console.log(items['1.9']); // undefined (brackets do no conversion)Code that calls at() with a value you didn't compute yourself, such as a query parameter or a field read from parsed JSON, can return the first element when the value is garbage. Validate such input first, for example with Number.isInteger(i).
at() is read-only
at() is a method call. It returns a value, not a reference to a slot, so you can't assign to it. items.at(-1) = 'z' is an error: an early SyntaxError in strict mode and modules, or a ReferenceError in some engines' sloppy mode. You have two ways to update an element counted from the end:
const steps = ['plan', 'build', 'test'];
// In place: compute the index yourself
steps[steps.length - 1] = 'ship';
console.log(steps); // ['plan', 'build', 'ship']
// As a copy: with() also accepts negative indexes (ES2023)
const revised = steps.with(-1, 'deploy');
console.log(revised); // ['plan', 'build', 'deploy']
console.log(steps); // ['plan', 'build', 'ship']with() gets a full section in a later chapter on copying methods. It differs from at() in one way: an out-of-range index makes with() throw a RangeError, while at() just returns undefined.
Edge cases
`undefined` is ambiguous
at() returns undefined in three situations: the index is out of range, the slot is a hole in a sparse array, or the element actually is undefined. If the difference matters to you, check the position yourself:
const data = [1, , undefined];
console.log(data.at(1)); // undefined (hole)
console.log(data.at(2)); // undefined (real value)
console.log(data.at(5)); // undefined (out of range)
console.log(1 in data); // false: position 1 is a hole
console.log(2 in data); // true: position 2 holds undefinedStrings and typed arrays
String.prototype.at() and the typed array versions follow the same rules:
console.log('hello'.at(-1)); // 'o'
console.log(new Uint8Array([5, 6, 7]).at(-1)); // 7
console.log('😀'.at(-1) === '\uDE00'); // trueThe last line shows a trap. String at() counts UTF-16 code units, not visible characters. An emoji takes two code units, so at(-1) returns half of it, a lone surrogate. To get the last full character, split the string into code points first: [...str].at(-1).
Array-like objects
at() is generic. It only needs a length property and numeric keys, so you can borrow it for objects that look like arrays but aren't:
const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 };
console.log(Array.prototype.at.call(arrayLike, -1)); // 'z'Support
at() is available in Node.js 16.6+ and in all current major browsers. If your code must run on older engines, use arr[arr.length - 1] or load a polyfill.
Choosing between at() and brackets
- Use brackets for writes and for ordinary forward indexing inside loops, where
iis known to be a valid integer. - Use
at()for reading from the end, especially at the end of a method chain. - Use
with()when you want a copy with an element replaced, counting from the end. - Avoid
at()on untrusted indexes unless you have validated them, because invalid values can quietly map to index0.
Exercise
Given const log = ['boot', 'load', 'run', 'halt'];, what do log.at(-4), log.at(-5), log.at(-0.5), and log[-1] return, and why?
Show answer
log.at(-4) returns 'boot', because 4 + (-4) = 0. log.at(-5) returns undefined, because 4 + (-5) = -1 is out of range. log.at(-0.5) returns 'boot', because -0.5 truncates toward zero to 0. log[-1] returns undefined, because brackets look up a property named "-1", which doesn't exist.
Exercise
A colleague writes history[-1] = newEntry; to replace the latest entry in an array. What happens, and what are two correct alternatives, one that mutates and one that doesn't?
Show answer
The code creates a non-index property named "-1". The array's elements and length stay the same, so the last entry is never replaced. To mutate, write history[history.length - 1] = newEntry;. To get a copy, write const updated = history.with(-1, newEntry);. Neither works on an empty array: the first creates a "-1" property and the second throws a RangeError.
Exercise
Write a function lastChar(str) that returns the last visible character of a string, and gives the correct result for 'hi😀'.
Show answer
const lastChar = str => [...str].at(-1); Spreading the string splits it by code points, so the emoji stays whole. 'hi😀'.at(-1) would return only the trailing surrogate half.