Syntax
arr.slice(start, end)
arr.splice(start, deleteCount, ...items)Examples
slice() - Non-Mutating Extraction
Extracting a portion of an array without changing the original.
const fruits = ["apple", "banana", "cherry", "date", "elderberry"];
console.log(fruits.slice(1, 3)); // ["banana", "cherry"] - end index excluded
console.log(fruits.slice(2)); // ["cherry", "date", "elderberry"] - to the end
console.log(fruits.slice(-2)); // ["date", "elderberry"] - last 2 elements
console.log(fruits); // original array is unchangedsplice() - Mutating Removal
Removing elements from an array, modifying it in place.
const numbers = [1, 2, 3, 4, 5];
const removed = numbers.splice(1, 2); // start at index 1, remove 2 elements
console.log(removed); // [2, 3] - the removed elements
console.log(numbers); // [1, 4, 5] - original array is mutatedsplice() - Inserting and Replacing
Using splice() to insert new elements or replace existing ones.
const colors = ["red", "green", "blue"];
// Insert without removing (deleteCount = 0)
colors.splice(1, 0, "yellow");
console.log(colors); // ["red", "yellow", "green", "blue"]
// Replace an element
colors.splice(2, 1, "purple");
console.log(colors); // ["red", "yellow", "purple", "blue"]Best practices
- Use slice() whenever you want a new array without mutating the original - it is the safer, more predictable choice
- Use splice() specifically when you need to remove or insert elements at a specific position in place
- Remember slice()'s end argument is exclusive - slice(1, 3) returns indices 1 and 2, not 3
- Save splice()'s return value if you need the removed elements - it returns them as a new array
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification