JavaScript Array.splice() - Insert, Remove, and Replace Elements
Complete guide to Array.splice() for inserting, removing, and replacing elements at any position. Includes visual examples and the ES2023 toSpliced() alternative. Free reference.
Mutation
Detailed Explanation
Understanding Array.splice()
Array.splice() is the most versatile mutating method. It can remove elements, insert elements, or replace elements at any position in the array — all in a single call.
Syntax
const removed = array.splice(start, deleteCount, item1, item2, ...);
- start — index where the operation begins
- deleteCount — how many elements to remove (0 to insert without removing)
- item1, item2, ... — elements to insert at the start position
Returns an array of removed elements.
Remove Elements
const arr = ["a", "b", "c", "d", "e"];
const removed = arr.splice(1, 2);
// arr: ["a", "d", "e"]
// removed: ["b", "c"]
Insert Elements
const arr = ["a", "c", "d"];
arr.splice(1, 0, "b");
// arr: ["a", "b", "c", "d"]
Replace Elements
const arr = ["a", "b", "x", "d"];
arr.splice(2, 1, "c");
// arr: ["a", "b", "c", "d"]
Negative Indices
Negative start values count from the end:
const arr = [1, 2, 3, 4, 5];
arr.splice(-2, 1);
// arr: [1, 2, 3, 5] (removed element at index -2 = index 3)
splice vs slice
| splice() | slice() | |
|---|---|---|
| Mutates? | Yes | No |
| Returns | Removed elements | New sub-array |
| Can insert? | Yes | No |
ES2023: toSpliced()
For immutable operations, use toSpliced():
const arr = ["a", "c", "d"];
const result = arr.toSpliced(1, 0, "b");
// result: ["a", "b", "c", "d"]
// arr: ["a", "c", "d"] (unchanged)
Use Case
Use splice() for managing ordered lists where items need to be added, removed, or replaced at specific positions. Common in drag-and-drop reordering, todo list management, and any in-place array modification scenario.