**splice(start, deleteCount, ...items)** is a Swiss-army knife for array mutation. It can remove, insert, or replace elements. It **mutates** the original array and returns an array of removed elements. For non-mutating alternatives, use **slice** and spread.
1Understanding Array.splice()
splice(start, deleteCount, ...items) is a Swiss-army knife for array mutation. It can remove, insert, or replace elements. It mutates the original array and returns an array of removed elements. For non-mutating alternatives, use slice and spread.
splice() MUTATES. Use filter() for non-mutating removal, or [...arr] spread for non-mutating insertion.
const arr = ['a', 'b', 'c', 'd', 'e'];
// Remove 2 items at index 1
const removed = arr.splice(1, 2);
console.log(removed); // ['b', 'c']
console.log(arr); // ['a', 'd', 'e']2Practical Example
Here is a real-world application of Array.splice() showing how it is used in production JavaScript code.
const arr2 = [1, 2, 3, 4, 5];
// Insert at index 2 (no removal)
arr2.splice(2, 0, 'x', 'y');
console.log(arr2); // [1, 2, 'x', 'y', 3, 4, 5]
// Replace index 0 with 'zero'
arr2.splice(0, 1, 'zero');
console.log(arr2); // ['zero', 2, 'x', 'y', 3, 4, 5]3Best Practices
Follow these guidelines when working with Array.splice():
1. Be aware splice mutates the original array
2. Use negative start index to count from the end
3. Prefer filter() for removing items without mutation
Tip: splice() MUTATES. Use filter() for non-mutating removal, or [...arr] spread for non-mutating insertion.
const arr = ['a', 'b', 'c', 'd', 'e'];
// Remove 2 items at index 1
const removed = arr.splice(1, 2);
console.log(removed); // ['b', 'c']
console.log(arr); // ['a', 'd', 'e']