Skip to content
jshacks.dev
Fundamentals

JavaScript Array at Method Reads From the End Without Math

Array at() takes a negative index and counts from the end, so the last item is at(-1). See how it differs from brackets, strings and out of range reads.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm, Vite and Node.js logos.

The most common way to read the last item of an array in JavaScript is arr[arr.length - 1], and it has one real defect: the array expression appears twice. When the array is the result of a function call, you either call it twice or you invent a temporary variable only to subtract one. Array.prototype.at() removes that. If you are working through the built-ins in order, the complete guide to modern JavaScript covers where at() sits among the ES2022 additions, and this post covers what it does at the edges.

On Node.js 24 and any current browser, at() takes one integer and returns the item at that position, counting from the end when the integer is negative.

JavaScript
const queue = ["parse", "validate", "enrich", "store"];

console.log(queue.at(0));
console.log(queue.at(2));
console.log(queue.at(-1));
console.log(queue.at(-2));
Text
parse
enrich
store
enrich

at(-1) is the last item, at(-2) the one before it. Positive indexes behave exactly like brackets.

Why brackets cannot do this

A negative number in square brackets is not an index at all. Bracket access converts its operand to a property key, and -1 becomes the string "-1". An array has no such property, so you get undefined, and no error tells you the code is wrong.

JavaScript
const queue = ["parse", "validate", "enrich", "store"];

console.log(queue[-1]);
console.log(queue.at(-1));
console.log(Object.keys(queue));
Text
undefined
store
[ '0', '1', '2', '3' ]

This is the mistake at() exists to absorb. Python programmers write items[-1] out of habit and get a silent undefined in JavaScript. With at() the habit works, as long as the method name is attached.

The fix has a cost worth stating: at() is a method call, so it is marginally more work than a property read for an engine that cannot inline it. We have not measured a difference that matters in application code, and you should not give up the clearer form for a guess about speed. In a hot loop over millions of items, profile before choosing either.

The out of range rule

An index beyond either end returns undefined. It does not wrap, clamp or throw.

JavaScript
const steps = ["a", "b", "c"];

console.log(steps.at(3));
console.log(steps.at(-4));
console.log(steps.at(100));
Text
undefined
undefined
undefined

That is the same result an out of range bracket read gives, which makes at() a safe drop-in. It also means the method cannot tell you "this slot is empty" apart from "this slot holds undefined". If your array can contain undefined on purpose, compare against length first.

JavaScript
function lastOrThrow(items) {
  if (items.length === 0) {
    throw new RangeError("expected at least one item");
  }
  return items.at(-1);
}

console.log(lastOrThrow([10, 20, 30]));
Text
30

For an empty array, at(-1) returns undefined, which is why a guard like that earns its three lines whenever the caller treats a missing last item as a bug.

What non-integer arguments do

The argument goes through the same conversion as the rest of the spec's integer arguments: it is converted to a number, then truncated toward zero. NaN becomes 0, and a string that parses as a number is accepted.

JavaScript
const letters = ["a", "b", "c", "d"];

console.log(letters.at(1.9));
console.log(letters.at(-1.9));
console.log(letters.at(NaN));
console.log(letters.at("2"));
console.log(letters.at());
Text
b
d
a
c
a

Two of those deserve attention. at(-1.9) returns "d", because truncation toward zero turns it into -1, not -2. And at() with no argument returns the first item, because a missing argument is undefined, which converts to NaN and then to 0. A caller that forgets to pass an index gets the head of the array and no warning. We would rather you never rely on either behavior, and the second is a reason to prefer a typed wrapper if the index comes from user input.

It works on strings and typed arrays too

at() was added to String.prototype and every typed array in the same proposal, so the habit carries over. On a string it counts UTF-16 code units, the same unit length uses, which matters the moment a character falls outside the Basic Multilingual Plane. Strings in JavaScript are UTF-16, and at() inherits that.

JavaScript
const word = "node";
console.log(word.at(-1));

const emoji = "a😀";
console.log(emoji.length);
console.log(emoji.at(-1) === "\ude00");

const bytes = new Uint8Array([7, 8, 9]);
console.log(bytes.at(-1));
Text
e
3
true
9

emoji.at(-1) returns a lone low surrogate, not the emoji. If you need the last character a person would see, use Array.from(emoji).at(-1) for code points, or Intl.Segmenter for grapheme clusters, covered in Unicode in JavaScript.

Using it on array-likes

The method is generic. It reads length and integer-keyed properties from whatever this is, so it works on arguments, a NodeList or a plain object shaped like an array.

JavaScript
const row = { 0: "id", 1: "name", 2: "email", length: 3 };

console.log(Array.prototype.at.call(row, -1));

function lastArgument() {
  return Array.prototype.at.call(arguments, -1);
}

console.log(lastArgument("a", "b", "c"));
Text
email
c

In a function that takes rest parameters you already have a real array, so write args.at(-1) and skip the call. The call form earns its place only for objects you do not own.

Replacing slice and length arithmetic

Before at(), the usual workarounds for reading from the end were arr[arr.length - 1], arr.slice(-1)[0] and a utility function. The slice variant allocates a new one-item array for each read. For the last item, at(-1) is shorter than all three and allocates nothing.

GoalBeforeWith at()
Last itemarr[arr.length - 1]arr.at(-1)
Second to lastarr[arr.length - 2]arr.at(-2)
Last item of a call resultconst r = f(); r[r.length - 1]f().at(-1)
Safe read with fallbackarr[arr.length - 1] ?? "none"arr.at(-1) ?? "none"

The last row keeps working the way you expect because ?? only replaces undefined and null. Pair it with nullish coalescing rather than ||, which would also replace a stored 0 or an empty string.

Pinning the behavior with a test

The edge cases above are the ones a refactor breaks, so they are worth a few lines of node:test. A codebase that moves from brackets to at() usually does it with a search and replace, and the replace is where arr[-1] bugs get preserved: someone sees arr[-1], assumes it was meant to be the last item and converts it, and the test fails because the original code never worked. Writing the assertions first makes that visible.

JavaScript
import { test } from "node:test";
import assert from "node:assert/strict";

test("at counts from the end", () => {
  const items = ["a", "b", "c"];
  assert.equal(items.at(-1), "c");
  assert.equal(items[-1], undefined);
});

test("at returns undefined out of range", () => {
  assert.equal([].at(-1), undefined);
  assert.equal(["a"].at(1), undefined);
});

test("at truncates toward zero", () => {
  assert.equal(["a", "b", "c"].at(-1.9), "c");
});

Run it with node --test on Node.js 24. All three pass, and the second one is the guard that tells you an empty queue is being treated as a value somewhere downstream.

Where at() is the wrong tool

at() reads. It does not write, so arr.at(-1) = x is a syntax error. To replace the last item you still write arr[arr.length - 1] = x, or use arr.with(-1, x) on a copy in runtimes that have Array.prototype.with, which also accepts negative indexes.

It is also unavailable on Node.js 14 and older, and on Safari before 15.4. If you still ship to those, a transpiler will not help, because this is a library method and not syntax; you need a polyfill. Check your support matrix before replacing every bracket expression in a codebase.

Finally, if you want a slice of the end and not one item, use slice(-3), which already accepts negative arguments. Array.prototype.find and its siblings are the better tool when you want the last item matching a condition and not the last item whatever it holds.

The behavior is defined in the ECMAScript specification under Array.prototype.at, and MDN keeps a version-by-version support table on its Array.prototype.at reference page.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.