The toSpliced(start, deleteCount, ...items) method, introduced in JavaScript ES2023, is a non-mutating version of the traditional splice method for arrays. It allows you to remove and/or insert elements at a specific index in an array without modifying the original array. Instead, it returns a new array with the specified changes applied.

Parameters

The method creates a new copy of the original array.

It removes deleteCount elements from the new array starting at the start index.

If any items are provided, it inserts them into the new array at the start index, replacing the removed elements (if any).

Finally, the method returns the newly created array with the spliced elements.

Benefits of toSpliced(start, deleteCount, ...items)

Example

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

// Remove two elements starting from index 2 and insert "a" and "b"
const splicedArray = originalArray.toSpliced(2, 2, "a", "b");

console.log(originalArray); // [1, 2, 3, 4, 5] (original array remains unchanged)
console.log(splicedArray);   // [1, 2, "a", "b", 5]

Output

Script.js output