DEV Community

Jack Huynh
Jack Huynh

Posted on

Javascript ( ES14 ): toSpliced()

ECMAScript proposal "Change Array by copy" by Robin Ricard and Ashley Claymore has been merge into ECMAScript standard. This proposal brings a lot of new toys, one of which is new array method: toSpliced().

The toSpliced() method is similar to splice

array.toSpliced(start, deleteCount, item1, item2, ...)

Enter fullscreen mode Exit fullscreen mode

The only difference is that it does not change the original array, calling this method returns a changed copy of the original array instead of the deleted array.

// splice()
const originalArr = [1,2,3];
const targetArr = originalArr.slice(1, 1, 5);

console.log(targetArr) // [2]
// The original array is mutated
console.log(originalArr) // [1,5,3]

// toSplice()
const originalArr = [1,2,3];
const targetArr = originalArr.toSplice(1, 1, 5);

console.log(targetArr) // [1,5,3];
// The original array is not affected
console.log(originalArr) // [1,2,3]
Enter fullscreen mode Exit fullscreen mode

For more information, check out the following resources:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSpliced

Top comments (0)