Skip to main content Accessibility Feedback

The new Array.prototype.toSpliced() method in vanilla JS

This week, we’re looking at new JavaScript methods in ES2023.

Yesterday, we covered the Array.prototype.toReversed() method. Today, we’re looking at the Array.prototype.toSpliced() method.

Let’s dig in!

Splicing arrays with the Array.prototype.splice() method

The Array.prototype.splice() method is used to add, remove, and replace items in an array. When using the method, the original array is modified.

The first argument is the index of the item you want to modify in the array, and is the only required argument. The second argument is the number of items to delete from the array. It can be a number from 0 through the length of the array.

If you omit the second argument, the Array.prototype.splice() method will delete every item in the array from the start index on.

let wizards = ['Merlin', 'Ursula', 'Gandalf', 'Radagast'];

// This removes 1 item at index 2: "Gandalf"
// wizards is now ["Merlin", "Ursula", "Radagast"]
wizards.splice(2, 1);

Historically, if you want to keep the original array intact, you would clone it first, then splice() it.

let fewerWizards = Array.from(wizards).splice(2, 1);

Creating a spliced copy of an array with the Array.prototype.toSpliced() method

The new Array.prototype.toSpliced() does the same thing as Array.prototype.splice(), but creates a copy instead of modifying the original array.

let wizards = ['Merlin', 'Ursula', 'Gandalf', 'Radagast'];
let lessWizards = wizards.toSpliced(2, 1);

// logs ['Merlin', 'Ursula', 'Gandalf', 'Radagast']

// logs ['Merlin', 'Ursula', 'Radagast']

Here’s a demo.

Browser support (and a polyfill)

While the Array.prototype.toSpliced() is supported in all major browsers, it’s 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.toSpliced) {
	Array.prototype.toSpliced = function (...args) {
		return Array.from(this).splice(...args);

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