DEV Community

Pablo
Pablo

Posted on • Edited on

16 5

sPlice !== slice

This is a short post for my future self.
Hi Pablo! Back here already? Yeah, I know, splice, slice, which one is it?? But don't worry, you've got this, only this time we're writting it down!

So, long story short: do you want your array to be mutated? Really? Well, go ahead, sPlice the hell out of it. See what I did there? Capital P, as in "Produces Side Effects, Pal!"

Why, you ask? Because...

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements.
see MDN Docs


Conversly, .slice() method will graciously return the desired data, keeping your beloved original array unmutated. Just tell it where to start and finish (optionally)... slice will comply, no questions asked:

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included) where begin and end represent the index of items in that array. The original array will not be modified. see MDN Docs

You can search the webs for examples and more in depth docs, but this should make it easier next time you hit the mental crossroad... splice or slice, you choose (wisely, now)...

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (3)

Collapse
 
deciduously profile image
Ben Lovy

Capital P, as in "Produces Side Effects, Pal!"

Wow, this is perfect. I constantly forget the difference. Thanks!

Collapse
 
pablowbk profile image
Pablo

Thank freeCodeCamp for making my brain hurt! Glad you liked it, Ben!

Collapse
 
nasimuddin01 profile image
Muhammad Nasim Uddin

Pablo, Great explaination. I always forget the difference between slice & splice. I hope now I can remember it for a more time than previous.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

👋 Kindness is contagious

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

Okay