brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: array.at(-1) gets the last item without array.length – 1

Javascript
~/tips/tip-javascript-array-at-negative-index

const items = ['a', 'b', 'c'];

Reads an array item by index and counts from the end when the index is negative.

Getting the last element of an array has always meant items[items.length - 1], which is easy to get wrong when the array is the result of a long expression.

const items = ['a', 'b', 'c'];
items.at(-1);  // 'c'
items.at(-2);  // 'b'
items.at(0);   // 'a'

at() accepts positive and negative integers. A negative number counts back from the last item. If the index is out of range it returns undefined, it does not throw.

Why not just items[-1]? MDN explains that square brackets treat the value as a property name, so you end up reading the property "-1", which does not exist on a normal array.

It shines on a chained call, where you do not want a temporary variable:

const lastWord = text.trim().split(' ').at(-1);

Strings and typed arrays have at() too, with the same rules.

The caveat is that at() only reads. To write with a negative index, MDN suggests combining it with with(), which returns a copy with one item changed, so items.with(-1, 'z') replaces the last one without touching the original. Also, the empty array gives undefined for every index, so check the length if that matters.

Further reading: MDN: Array.prototype.at()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link