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
- start: The index at which to start splicing (removing or inserting elements).
- deleteCount: The number of elements to remove from the original array starting at the start index.
- ...items: (Optional) The elements to insert at the specified start index. You can provide zero or more items to insert.
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)
- Immutability: Preserves the original array, preventing accidental modifications and promoting functional programming practices.
- Clarity: Makes the code more readable and understandable by explicitly specifying the changes to be made.
- Chaining: Can be chained with other non-mutating array methods for concise data manipulation.
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