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

shelly agarwal @shelly_agarwal_19

About: 5+ years expertise on Frontend. Hands-on ReactJS, React Native, etc. | Build cool projects with me Instagram profile: https://www.instagram.com/code_yourself_?igsh=MWZmcXNlOHVjYzZrbQ%3D%3D&u

Location:
Udaipur, Rajasthan
Joined:
Mar 3, 2025

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

Publish Date: Mar 31
3 0

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! 🙋‍♀️

Comments 0 total

    Add comment