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)...

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up