🏗️

splice()

🎉
💨
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"];
2
3// splice(start, deleteCount, ...itemsToAdd)
4
5// Remove 2 items starting at index 1
6arr.splice(1, 2);
7// arr is now ["A", "D", "E"]
8// Returns removed items: ["B", "C"]
9
10// Insert items at index 1 (delete 0)
11arr.splice(1, 0, "X", "Y");
12// arr is now ["A", "X", "Y", "D", "E"]
13
14// Replace: delete 1, add 1
15arr.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.

🏗️
[
A
[0]
B
[1]
C
[2]
D
[3]
E
[4]
]
length: 5