Slice it or splice it?
Similar names different behaviour
Both, slice
and splice
are methods used to manipulate arrays.
Due to their similar name, they are often confused with each other (in particular by non-native speakers).
Let's take a look at them.
Slice
The slice
method is used to extract a section of an array (or a string) and returns a shallow copy with the selected elements.
It doesn't affect the initial array.
It takes two zero-based, optional parameters:
- start - index from which to start copying
- end - index where the copying ends (this element is not considered)
Here's an example of usage:
const arr = [0, 1, 2, 3, 4, 5];
console.log(arr.slice(3));
// Output: [3, 4, 5]
console.log(arr.slice(1, 4));
// Output: [1, 2, 3]
console.log(arr.slice(-2));
// Output: [4, 5]
Splice
The splice
method modifies an initial array by removing selected items and optionally inserting new ones.
An array containing the deleted elements is returned.
It takes three arguments:
- start - Index at which to start changing the array.
- deleteCount - Indicates the number of elements to remove.
- item1, item2, ... - The elements to add to the array (from the start index).
Example usage:
const arr = [0, 1, 2, 3, 4, 5];
const removed = arr.splice(1, 3, 99, "xyz");
// arr is [0, 99, "xyz", 4, 5]
// removed is [1, 2, 3]
Key differences
Slice | Splice |
---|---|
Used to get subset of original array | Used to delete, modify or insert data to array |
Doesn't modify original array | Modifies original array |
Returns selected items | Returns deleted items |