Skip to main content

What does toSpliced() do?

The toSpliced() method is a new non-mutating counterpart to the old splice() method (added in ECMAScript 2023 / ES14).

It performs removal, insertion, or replacement of elements, but does not change the original array, returning a new copy with the changes instead.


Syntax:

javascript
const newArray = array.toSpliced(start, deleteCount, ...items);
ParameterDescription
startThe index at which the changes begin
deleteCountHow many elements to remove
...itemsThe elements to insert at that position (optional)

1. Removing elements

javascript
const arr = [1, 2, 3, 4, 5]; const newArr = arr.toSpliced(1, 2); // remove 2 elements starting at index 1 console.log(newArr); // [1, 4, 5] console.log(arr); // [1, 2, 3, 4, 5] - the original is unchanged
  • Removed [2, 3]
  • Got a new array [1, 4, 5]
  • The original stays untouched

2. Inserting elements

javascript
const arr = [1, 2, 3]; const newArr = arr.toSpliced(1, 0, "a", "b"); console.log(newArr); // [1, "a", "b", 2, 3] console.log(arr); // [1, 2, 3]
  • Starting at index 1, nothing is removed (deleteCount = 0)
  • "a" and "b" are inserted
  • A new array is returned, the original does not mutate.

3. Replacing elements

javascript
const arr = [1, 2, 3, 4]; const newArr = arr.toSpliced(1, 2, "x", "y"); console.log(newArr); // [1, "x", "y", 4] console.log(arr); // [1, 2, 3, 4]
  • Removed [2, 3]
  • Inserted "x", "y"

4. Comparison with splice()

javascript
const arr = [1, 2, 3, 4]; const mutated = arr.splice(1, 2, "x", "y"); console.log(arr); // [1, "x", "y", 4] - the original is changed console.log(mutated); // ["2", "3"] - returns the removed elements const newArr = [1, 2, 3, 4].toSpliced(1, 2, "x", "y"); console.log(newArr); // [1, "x", "y", 4] - a new array

When to use it

  • When you need to change an array without side effects (for example, in React, Redux, or any immutable code).
  • When it's important to keep the original data intact.

New methodOld counterpartWhat it doesChanges the array
toReversed()reverse()ReversesNo
toSorted()sort()SortsNo
toSpliced()splice()Removes / insertsNo
with()arr[index] = valueChanges an element by indexNo

In short:

What it doesCreates a new version of the array with elements removed / added
Changes the original arrayNo
ReturnsA new array
Supports insertion and replacementYes
Added inECMAScript 2023
Example[1,2,3].toSpliced(1,1,"X") -> [1,"X",3]

Summary: toSpliced() is a non-mutating counterpart to splice() that returns a new copy of the array with the desired changes, leaving the original unchanged.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.