Splice vs Slice in JavaScript: Key Differences and Usage
splice modifies the original array by adding or removing elements, while slice returns a new array with selected elements without changing the original. Use splice for in-place changes and slice for copying parts of an array.Quick Comparison
Here is a quick side-by-side comparison of splice and slice methods in JavaScript arrays.
| Feature | splice | slice |
|---|---|---|
| Modifies original array? | Yes | No |
| Returns new array? | Yes (removed elements) | Yes (selected elements) |
| Parameters | start index, delete count, items to add (optional) | start index, end index (optional) |
| Use case | Add/remove elements in place | Copy part of array without change |
| Negative indices support | Yes (counts from end) | Yes (counts from end) |
| Effect on array length | Changes length | Does not change length |
Key Differences
The splice method changes the original array by removing or adding elements starting at a specified index. It takes at least two arguments: the start index and the number of elements to remove. You can also add new elements at that position. Because it modifies the array directly, it affects the array's length.
On the other hand, slice does not change the original array. It returns a new array containing elements from the start index up to, but not including, the end index. If the end index is omitted, it slices until the array's end. This method is useful when you want to copy part of an array without altering the original.
Both methods accept negative indices, which count from the end of the array. However, their purposes differ: splice is for editing the array in place, while slice is for extracting a portion safely.
Code Comparison
Here is how you remove elements from an array using splice:
const fruits = ['apple', 'banana', 'cherry', 'date', 'fig']; const removed = fruits.splice(1, 2); console.log('Removed:', removed); console.log('Fruits after splice:', fruits);
Slice Equivalent
Here is how you get a part of the array using slice without changing the original:
const fruits = ['apple', 'banana', 'cherry', 'date', 'fig']; const part = fruits.slice(1, 3); console.log('Sliced part:', part); console.log('Fruits after slice:', fruits);
When to Use Which
Choose splice when you need to add or remove elements directly in the original array, such as editing a list in place. It is perfect for tasks like deleting items or inserting new ones at specific positions.
Choose slice when you want to create a new array from part of an existing one without changing the original. This is useful for safe copying or extracting subarrays for further use.
Key Takeaways
splice changes the original array by adding/removing elements.slice returns a new array and leaves the original unchanged.splice for in-place edits and slice for copying parts.splice affects array length; slice does not.