DEV Community

Cover image for splice() vs toSpliced() which one to prefer in javascript?
shelly agarwal
shelly agarwal

Posted on

splice() vs toSpliced() which one to prefer in javascript?

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)

Enter fullscreen mode Exit fullscreen mode
toSplicedResponse: [2,3,4]
Enter fullscreen mode Exit fullscreen mode
  • Works like splice() only but doesn't mutate toSplicedResponse array.
  • 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)

Enter fullscreen mode Exit fullscreen mode
splicedResponse: [2,3,4]
data: [1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

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);

Enter fullscreen mode Exit fullscreen mode
data: [2,3,4]
Enter fullscreen mode Exit fullscreen mode

data is 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)