Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Get the last array element with at() in JavaScript

74 at, and the negative index brackets cannot reach

easy

Read the last, second-to-last and first elements of a list with at, and compare each with what square brackets do. Then check four edge cases: a negative zero, a fractional index, an index past the end on a string, and what at gives you in the middle of a surrogate pair.

Stuck? Three hints, smallest first
  1. 1. list[-1] is not an index. It is a property lookup for the key "-1", which nothing set.
  2. 2. at counts a negative index back from length, and returns undefined when it lands outside the array.
  3. 3. charAt returns an empty string for an index that does not exist; at returns undefined.

The answer

const readings = [12, 45, 78, 91, 103];

const last = readings.at(-1);
const penultimate = readings.at(-2);
const firstOne = readings.at(0);
const bracketMinusOne = readings[-1];
const oldWay = readings[readings.length - 1];

const pastTheEnd = readings.at(5);
const wayBefore = readings.at(-9);
const negativeZero = readings.at(-0);
const fractional = readings.at(1.7);
const notANumber = readings.at('2');

const lga = 'Ikeja';
const lastLetter = lga.at(-1);
const charAtPastEnd = lga.charAt(99);
const atPastEnd = lga.at(99);

const flag = '🇳🇬';
const halfAPair = flag.at(-1);
const wholePoint = Array.from(flag).at(-1);
const pieceSizes = [halfAPair.length, wholePoint.length];

const arrayLike = { length: 2, 0: 'Lagos', 1: 'Kano' };
const borrowed = Array.prototype.at.call(arrayLike, -1);

console.log('at     :', last, penultimate, firstOne);
console.log('bracket:', bracketMinusOne, '| the old way:', oldWay);
console.log('edges  :', pastTheEnd, wayBefore, negativeZero, fractional, notANumber);
console.log('string :', lastLetter, JSON.stringify(charAtPastEnd), atPastEnd, '| borrowed:', borrowed);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a negative index counts back from the end', [last, penultimate, firstOne], [103, 91, 12]);
test('brackets cannot: [-1] is a property name, not a position', [bracketMinusOne === undefined, oldWay], [true, 103]);
test('an index outside the array is undefined in either direction', [pastTheEnd === undefined, wayBefore === undefined], [true, true]);
test('minus zero is zero, and a fractional index is truncated towards zero', [negativeZero, fractional], [12, 45]);
test('the index is coerced, so a numeric string works', notANumber, 78);
test('on a string at gives one character back, counted from the end', lastLetter, 'a');
test('charAt answers a missing index with an empty string; at says undefined', [charAtPastEnd, atPastEnd === undefined], ['', true]);
test('at indexes UTF-16 units, so it can hand you half a code point', pieceSizes, [1, 2]);
test('and it is generic, so an array-like can borrow it', borrowed, 'Kano');

at exists for one reason: list[-1] silently does the wrong thing. Square brackets take a property key, so -1 becomes the string "-1", which no array has, and you get undefined with no complaint. Before at, the last element meant list[list.length - 1], or list.slice(-1)[0], which allocates an array to throw it away.

It is a plain index read, not a smarter one. Fractional indices are truncated, string indices are coerced to numbers, and anything landing outside the bounds is undefined — including at(-9) on a five-element array, which does not wrap around. On a string it still counts UTF-16 units, so the last "character" of a flag or an emoji is half a surrogate pair; go through Array.from or spread first if code points are what you mean.

Like most array methods it is generic. Array.prototype.at.call(arrayLike, -1) works on anything with a length, and String.prototype.at is the same idea for text. Nothing here mutates, so it is safe to reach for anywhere.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.