Skip to main content Accessibility Feedback

How to copy and replace a value in an array with the new Array.prototype.with() JavaScript method

This week, we’re looking at new Array methods in the ES2023 version of vanilla JavaScript.

So far, we’ve learned about how to copy and reverse an array with the Array.prototype.toReversed() method, and how to copy and splice and array with the Array.prototype.toSpliced() method.

Today, let’s learn how to copy and array and replace one of its values with the Array.prototype.with() method.

The old-school way to copy an array and swap a value

Let’s imagine you have an array of wizards, like this…

let wizards = ['Merlin', 'Ursula', 'Harry Potter', 'Radagast'];

You want to create a new array, and replace Harry Potter with the far more talented Hermione.

Traditionally, you would that by copying the array, then using bracket notation to update a value, like this…

let betterWizards = Array.from(wizards);
betterWizards[2] = 'Hermione';

Using the Array.prototype.with() method

Using the new Array.prototype.with() method, you can do the same thing in a single operation.

You pass in the index to replace and the value to replace it with as arguments. It creates a copy of the original array and swaps out the value.

let betterWizards = wizards.with(2, 'Hermione');

Here’s a demo.

Browser support (and a polyfill)

Just like the other methods in this series, the Array.prototype.with() is supported in all major browsers, but is still too new to use without a polyfill (in my opinion).

Here’s a polyfill you can use until browser support catches up…

if (!Array.prototype.with) {
	Array.prototype.with = function (index, value) {
		let copy = Array.from(this);
		copy[index] = value;
		return copy;
	};
}

Once it does, you can delete the polyfill without having to refactor your code.