DEV Community

Vivek Kumar
Vivek Kumar

Posted on

11 1

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

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

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay