JavaScript: slice vs splice
I have been asked a simple question several times “What is the difference between Slice and Splice in JavaScript?”. But since these two functionalities sound similar, it confuses many developers.
Splice and Slice, both are built-in Javascript Array functions.
How both the functions work?
Array.prototype.slice(startIndex[, endIndex])
slice() method returns a copy of a portion of the array without mutating the original array depending on the parameters provided.
It accepts two arguments i.e., startIndex and endIndex. Both are the indices of array elements. Example:
Array.prototype.splice(startIndex [, deleteCount[, item1[, item2[, …]]]])
splice() method returns a copy of a portion of the array by mutating (removing or replacing) the existing elements of the original array depending on the provided arguments.
It accepts n number of arguments.
startIndex
startIndex is the index at which to start changing the array.
deleteCount (Optional)
deleteCount is the number of elements in the array to be removed starting from from startIndex. If deleteCount has not been provided, then it will consider till the last element of the array.
item1, item2 …. (Optional)
All the arguments after second argument, are considered as insert elements at the place of startIndex.
Below are few code examples of removing and replacing elements of an array:
Differences
Basic differences are:
- slice is used to get a portion of array without mutating the original array whereas splice is used to replace or remote items from an array.
- Both return array of selected elements