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.with(index, value) replaces one item without changing the original

Web-Development
~/tips/tip-javascript-array-with

const arr = [1, 2, 3, 4, 5];

Returns a copy of an array with one index replaced, so the original stays unchanged.

Updating one item in a list without mutating it used to mean a copy first: const copy = [...arr]; copy[2] = x;. Two lines for one change. Array.prototype.with() does it as one expression. I’d rather read one line than a copy-then-assign pair.

It returns a new array with the item at the given index replaced and leaves the original alone:

const arr = [1, 2, 3, 4, 5];

arr.with(2, 6);   // [1, 2, 6, 4, 5]
arr;              // [1, 2, 3, 4, 5], untouched
arr.with(-1, 10); // [1, 2, 3, 4, 10]

Negative indexes count from the end, like at(). Because it returns an array you can chain it, which is where it shines in state updates for UI code where mutating state is a bug:

const next = todos.with(index, { ...todos[index], done: true });

It belongs to the same family as toSorted(), toReversed() and toSpliced(): the copying versions of methods that normally change the array in place.

Two caveats. First, an index outside the array throws a RangeError instead of quietly growing the array like arr[10] = 0 would:

[1, 2, 3].with(10, 0); // RangeError

Second, the result is always a dense array, so empty slots in a sparse array become undefined. The copy is also shallow, so objects inside are still shared with the original, which is why the todo example above spreads the object.

It has been in all major browsers since July 2023. For older targets you need a transpiler or a fallback.

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

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link