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);| Parameter | Description |
|---|---|
start | The index at which the changes begin |
deleteCount | How many elements to remove |
...items | The 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 arrayWhen 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.
Related non-mutating methods (ES2023+)
| New method | Old counterpart | What it does | Changes the array |
|---|---|---|---|
toReversed() | reverse() | Reverses | No |
toSorted() | sort() | Sorts | No |
toSpliced() | splice() | Removes / inserts | No |
with() | arr[index] = value | Changes an element by index | No |
In short:
| What it does | Creates a new version of the array with elements removed / added |
|---|---|
| Changes the original array | No |
| Returns | A new array |
| Supports insertion and replacement | Yes |
| Added in | ECMAScript 2023 |
| Example | [1,2,3].toSpliced(1,1,"X") -> [1,"X",3] |
Summary:
toSpliced()is a non-mutating counterpart tosplice()that returns a new copy of the array with the desired changes, leaving the original unchanged.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.