DEV Community

Vivek Kumar
Vivek Kumar

Posted on

Javascript .splice() vs .toSpliced()

In this tutorial, we will learn how .toSpliced() method can be handy.
You might have used JavaScript array splice method.

Lets have a look at how .splice() works then we will understand how .toSpliced() is different from it.

Splice

We can use splice when we want to remove some item from array.

Below code example shows what happens when we remove array items using .splice().
Removing items using splice

Below code example shows what happens when we add array items using .splice().
Adding items using splice

One thing which is important to notice here is, arr.splice() always returns removed Items.
You can also add and remove items at the same time but the output of arr.splice() will always be removed items.

And it modifies the actual array.

toSpliced

Array .toSpliced() also accepts the same parameter as .splice().
But the first difference is it won't modify the original array instead it will return the updated array.

Below code example shows what happens when we remove array items using .toSpliced().

removing items using .toSpliced()

Below code example shows what happens when we add array items using .toSpliced().

adding items using toSplice

Top comments (3)

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€ • Edited

I’m loving all these new to methods, truely none destructive πŸ™Œ

Collapse
 
mattg0 profile image
Matt Goodwin

Awesome!

Collapse
 
dsaga profile image
Dusan Petkovic

Good one, keep it up