JavaScript slice vs splice: Key Differences Explained
While Array.prototype.slice() and
Array.prototype.splice() share similar names in JavaScript,
they serve fundamentally different purposes when handling array data.
The key distinction lies in mutation: slice() extracts a
section of an array and returns a new array without altering the
original, whereas splice() directly modifies the original
array by adding, removing, or replacing elements.
Array.prototype.slice()
The slice() method returns a shallow copy of a portion
of an array into a new array object. It is a non-mutating (pure) method,
meaning the original array remains untouched.
Syntax
array.slice(startIndex, endIndex)startIndex(optional): The zero-based index at which to begin extraction. If negative, it indicates an offset from the end of the array.endIndex(optional): The zero-based index before which to end extraction. The element atendIndexis not included. If omitted, extraction continues to the end of the array.
Example
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
// Extract from index 1 up to (but not including) index 3
const slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // ['banana', 'cherry']
console.log(fruits); // ['apple', 'banana', 'cherry', 'date', 'elderberry'] (unchanged)Array.prototype.splice()
The splice() method alters the contents of an array by
removing existing elements and/or adding new elements in place. It is a
mutating (impure) method that changes the original array.
Syntax
array.splice(startIndex, deleteCount, item1, item2, ...)startIndex: The index at which to start changing the array.deleteCount(optional): An integer indicating the number of elements to remove fromstartIndex. If0, no elements are removed.item1, item2, ...(optional): Elements to add to the array, beginning fromstartIndex.
Return Value
splice() returns a new array containing the elements
that were removed. If no elements were removed, it returns an empty
array.
Example
const fruits = ['apple', 'banana', 'cherry', 'date'];
// Remove 2 elements starting from index 1, and insert 'orange'
const removedFruits = fruits.splice(1, 2, 'orange');
console.log(removedFruits); // ['banana', 'cherry']
console.log(fruits); // ['apple', 'orange', 'date'] (mutated)Summary Comparison
| Feature | Array.prototype.slice |
Array.prototype.splice |
|---|---|---|
| Mutates Original Array | No | Yes |
| Primary Use Case | Extracting elements | Adding, removing, or replacing elements |
| Arguments | (startIndex, endIndex) |
(startIndex, deleteCount, ...itemsToAdd) |
| Return Value | A new array with extracted elements | A new array with deleted elements |