'splice()' and 'slice()' are two array techniques in JavaScript that are often confused with each other. In order to resolve these ambiguities, we will compare the two methods below step by step.
1. Creating a Slice: The Simple Version
Purpose
Evaluates only a small part of an array without changing it.
Usage
array.slice(startIndex, endIndex);
Main Points
- Produces a new array consisting of the elements from startIndex to endIndex (not inclusive).
- Changes made to the original array are not visible.
- If indexes are negative, they count from the end.
- If no arguments are given, then array.slice() makes a shallow copy of the entire array.
Example
const fruits = ['apple', 'banana', 'cherry', 'date'];
const sliced = fruits.slice(1, 3);
console.log(sliced); // ['banana', 'cherry']
console.log(fruits); // ['apple', 'banana', 'cherry', 'date'] (that's how it remained)
2. splice(): Add/Remove Elements from an Array
Purpose
Alters the original array, inserts or deletes elements.
Syntax
array.splice(startIndex, deleteCount, item1, item2,...);
Key Points
- Changes the original array.
- Returns an array followed by the removed elements (if any).
- Deleting, adding or changing elements on the spot are all possible.
Examples
a. Deleting Elements
const numbers = [1, 2, 3, 4, 5];
const removed = numbers.splice(1, 2); // Start removing from position 1 and remove 2 from that
console.log(removed); // [2, 3]
console.log(numbers); // [1, 4, 5]
b. Adding Elements
const colors = ['red', 'blue'];
colors.splice(1, 0, 'green'); // Add 'green' after index 1 without deleting anything
console.log(colors); // ['red', 'green', 'blue']
c. Replacing Elements
const letters = ['a', 'b', 'c'];
letters.splice(1, 1, 'x'); // Replace 'b' with 'x' at index 1
console.log(letters); // ['a', 'x', 'c']
3. The Key Differences
Feature | slice() | splice() |
---|
Mutates Original | No | Yes |
Return Value | New array of extracted elements | Array of removed elements (if any) |
Parameters | (start, end) | (start, deleteCount, items...) |
Use Case | Copy a piece of an array | Add/remove elements in place |
- Slice Use it when you need to take a part from the array out without changing the original.
- Example: Generate a copy of an array:
- const copy = arr.slice();
- Splice Use it when you need to remove, add, or adjust an array.
- Example: Update a list dynamically, such as editing a to-do list.
5. Pitfalls of Using These Two Methods
Mixed Parameters Puzzle
- Slice (1, 3) obtains elements from indices 1 and 2 (excluding index 3).
- Splice (1, 3) starts at index 1 and removes three elements.
Splice's Mutability
- Splice() changes the original array, so always make sure you don't need to preserve the original data before using it.
Summary
- Slice: copy parts of an array without changing the original.
- Splice: can edit an array directly, deleting, introducing or replacing parts.