What is the difference between slice and splice?
Quick Answer
slice(start, end) returns a shallow copy of a portion of the array and doesn't change the original. splice(start, deleteCount, ...items) mutates the array — removing and/or inserting elements in place — and returns the removed elements.
The names are similar but one mutates and one doesn't. slice returns a copy of a chunk of the array and leaves the original alone. splice changes the array in place — you give it a start index, how many to remove, and optionally items to insert, and it returns whatever it removed. So in something like Redux where I need immutability, I use slice or spread, never splice. An easy mnemonic: splice has the extra letter and does the extra damage.
[1,2,3,4].slice(1,3)→[2,3]; original unchanged.arr.splice(1, 2)→ removes 2 elements from index 1, returns them, and shortensarr.arr.splice(1, 0, 'x')→ inserts'x'at index 1, deletes nothing.- For immutable updates (React/Redux state) use
slice, spread,filter,map— neversplice. - Also
String.prototype.sliceexists; strings have nosplice.