Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Modify JavaScript Arrays Immutably with `toSpliced()`

1 min read .
Modify JavaScript Arrays Immutably with `toSpliced()`

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)
  • start is the index where the change begins.
  • deleteCount controls how many existing elements are removed.
  • items are 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.

Related Posts

chevron-up