🎉
💨
The Swiss Army knife of arrays! Remove, add, or replace items anywhere!
The splice() Method
The splice() method can remove, add, or replace items at any position.
Unlike slice(), splice() changes the original array!
💡
💨
How splice() Works
1const arr = ["A", "B", "C", "D", "E"];23// splice(start, deleteCount, ...itemsToAdd)45// Remove 2 items starting at index 16arr.splice(1, 2);7// arr is now ["A", "D", "E"]8// Returns removed items: ["B", "C"]910// Insert items at index 1 (delete 0)11arr.splice(1, 0, "X", "Y");12// arr is now ["A", "X", "Y", "D", "E"]1314// Replace: delete 1, add 115arr.splice(2, 1, "Z");16// arr is now ["A", "X", "Z", "D", "E"]
🤔
💨
splice() vs slice()
splice()
- Changes original array
- Returns removed items
- Can add new items
slice()
- Keeps original intact
- Returns a copy
- Only reads, no changes
🎮
Try It Yourself!
Try different splice operations! Watch items get removed, added, or replaced.