An Interest In:
Web News this Week
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
No more confusion Splice vs Slice in Javascript
They were built for different purposes but they look same in several scenarios. I will clear confusion first instead of dragging it to the end of the article.
Tip 1: Look at their meanings
Splice:
join or connect (a rope or ropes) by interweaving the strands at the ends.
Slice:
cut (something, especially food) into slices.
Ok. First I should thank Google for their meanings. Thank you, Google.
Hope you got cleared to some extent.
Tip 2: Not a very intuitive tip but it is worth clearing your confusion a little more. Splice
text length
is greater than the slice
. Based on which remember, the splice can take more params when compared to slice. See the declaration here:
arr.splice(start, deleteCount, item1, item2, ..., itemN);
arr.slice(start, end);
Tip 3: It's a technical tip here. Splice mutates original array whereas slice wont.
Just remember, if someone asks bread slice what would you do.
Dont need to remember every tip. Just remember one that caught your attention.
Also, if you have remembered in another way. Please do comment.
Now, tech stuff. What do they really do?
Splice first:
It is an array method that works only on JS arrays. It removes, replaces, and/or adds new elements in the array.
mutates original array.
splice(start, deleteCount, item1, item2, ..., itemN);
start
where to start changing the array.
deleteCount
no.of elements to remove from the start and is optional.
item1, item2 and so on
to add elements to the array after the start.
splice returns removed items in an array if none then returns an empty array.
I hope, the above examples covered all scenarios. If you find any more interesting scenarios, please comment. I am very much happy to update the article with your suggestion any time.
Slice now
Slices the array and returns a shallow copy.
Doesnt mutate (alter) the original array
slice(start, end); - slice from start (including) to end (excluding) and accepts negative values.
Similar to slice in Array, there is a slice in String as well. Which also acts in the same manner but works on strings.
Thank you.
Original Link: https://dev.to/urstrulyvishwak/no-more-confusion-splice-vs-slice-in-javascript-1i2g
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To