JavaScript has two similar array methods: splice() and toSpliced(). But they behave differently! Let’s break it down.
How to understand which method to use when?
using toSpliced() – Returns a New Array (Immutable)
const toSplicedResponse =[1,2,3,4];
toSplicedResponse.toSpliced(0,1);
console.log("toSplicedResponse",toSplicedResponse)
toSplicedResponse: [2,3,4]
- Works like splice() only but doesn't mutate
toSplicedResponsearray. - Returns a new array (immutable approach)
using splice() – Mutates the Original Array
You need to use spread operator in order to avoid mutating existing array.
const data =[1,2,3,4];
const splicedResponse = [...data];
splicedResponse.toSpliced(0,1);
console.log("splicedResponse",splicedResponse)
console.log("data",data)
splicedResponse: [2,3,4]
data: [1,2,3,4]
If you don't use spread operator, it will cause data manipulation of actual state.
const data =[1,2,3,4];
data.toSpliced(0,1);
console.log("data",data);
data: [2,3,4]
datais now manipulated and we can't go back.
- Removes 1 element starting at index 0
- Modifies the original array!
📌 Use splice() when you need to modify an array in place.
📌 Use toSpliced() when you prefer immutability (React, functional programming).
Which one do you use more? Let’s discuss! 🙋♀️
Top comments (0)