Modify JavaScript Arrays Immutably with `toSpliced()`
1
min read .
Updated on
toSpliced() creates a modified copy of an array without changing the source array. It is the non-mutating counterpart to splice().
Syntax
array.toSpliced(start, deleteCount, ...items)startis the index where the change begins.deleteCountcontrols how many existing elements are removed.itemsare inserted at that position.
Replace Elements
const fruits = ['apple', 'banana', 'cherry', 'date'];
const updated = fruits.toSpliced(1, 2, 'blueberry', 'fig');
console.log(updated); // ['apple', 'blueberry', 'fig', 'date']
console.log(fruits); // unchanged
Insert Without Deleting
const numbers = [1, 2, 5];
const result = numbers.toSpliced(2, 0, 3, 4);
console.log(result); // [1, 2, 3, 4, 5]
Remove Elements
const values = ['a', 'b', 'c', 'd'];
const result = values.toSpliced(1, 2);
console.log(result); // ['a', 'd']
Why It Is Useful
Non-mutating updates are especially helpful in UI state management, reducers, and code where several consumers share the same array reference. toSpliced() makes that intent explicit without manually combining slices.
For older runtimes, an equivalent pattern may use spread syntax and slice, or clone an array before calling splice().
Conclusion
Use toSpliced() when you need insertion, removal, or replacement semantics without mutating the original array. It makes copy-on-change array updates concise and predictable.