Confusing splice and slice

Mar 1, 2021 · 2 min read · 306 Words · -Views -Comments

As a frontend developer, I’ve used these two functions frequently over the past few years but have always confused them. I always need to check the API or TS definitions. The best way is to remember them thoroughly. After all, we remember Marvel heroes clearly. So, I just haven’t put in enough effort.

Here I’ll mark down the differences between them for memory.

splice

Word Meaning

“Splice” means to join together by interweaving.

Function Explanation

Array.prototype.splice()

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

So, when you need to add, remove, or modify array elements, you can use this method.

Note that this function will modify the array itself.

slice

Word Meaning

“Slice” means a thin piece cut from something.

Function Explanation

String.prototype.slice()

The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.

Array.prototype.slice()

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

So, when you need to extract a subset from a string or array, you can use this method.

Note that this function will not modify the original string or array. For arrays, slice returns a shallow copy.

Conclusion

From the above explanation, we can see that splice is only available for arrays, while slice is implemented for both strings and arrays.

Final Thoughts

  • In addition to these two functions, there’s also a similar split function, but since it’s more commonly used, it’s not confusing.
  • I have to say that understanding while using them more will help reinforce memory of these boring knowledge points.
Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover