Arrays: Slice vs. Splice
slice and splice sound identical, do opposite things, and return different objects. One mutates the original array; the other doesn't. Here's a plain comparison before you mix them up again.
Although the two array methods slice and splice sound similar, they do different things, take different arguments, treat the original array differently, and return different objects. If that weren't enough, slice also works on strings, but splice doesn't! Here's a quick comparison between the two.
| Array.prototype.slice | Array.prototype.splice | |
|---|---|---|
| Signature | (startPosition, stopPosition) | (startPosition, count, elementsToAdd) |
| Description | Removes count number of elements, starting from the element at index startPosition, then adds the elementsToAdd, a comma-delimited list of arguments. | |
| Original Array | Unmodified | Modified |
| Return |
Comparison by Example
Slice
When slice is called, it:
- Makes a shallow copy of elements in the original array
- Leaves the original array unchanged
- Returns an array of the copied elements
- If the end position is not specified... (tbd)
- If the end position is specified, the element at that index is not included in the slice.
- Negative numbers are indices from the end of the array
- Removes
countnumber of elements from the array - Returns an array of the removed elements (possibly empty)
- Inserts new elements into the array
fruits = ['apples', 'oranges', 'banana', 'pear', 'grape'];
basket = fruits.slice(2, 3);
//fruits = [ 'apples', 'oranges', 'banana', 'pear', 'grape' ]
//basket = [ 'banana' ]It is worth noting that:
Splice
When splice is called, it:
fruits = ['apples', 'oranges', 'banana', 'pear', 'grape'];
basket = fruits.splice(2, 3);
//fruits = [ 'apples', 'oranges' ]
//basket = [ 'banana', 'pear', 'grape' ]Application
Slice
Slice is a useful tool to perform a shallow copy of an array, or array-like objects. It is commonly used like this:// The following doesn't work because arguments is not an array and does not have a slice() method
// args = arguments.slice();
args = Array.prototype.slice.call(arguments);Although arguments is not an array, you can pass it in this manner to convert it to an array.
Underscore's function functions are a good place to see this pattern in practice.
Splice
Splice can be used to insert, remove, or replace elements in an array.When one or two arguments are passed, it performs a remove operation.
If more than two arguments are passed and the count argument is 0, it effectively performs an insert at the startPosition.
If the count argument is not 0, it performs an insert after elements are removed, effectively a replace.