splice() for Replacing Elements
You'll learn how to replace existing array elements in one operation using splice().
You've seen how splice() can remove elements and how it can insert new ones. Now comes its most powerful trick: doing both at once to replace elements in place.
Combining Deletion and Insertion
When you provide three or more arguments to splice(), you're telling it: "Remove some items starting here, and insert these new items in their place."
The syntax looks like this:
array.splice(startIndex, deleteCount, item1, item2, ...);
startIndex: where to start the replacementdeleteCount: how many elements to removeitem1, item2, ...: the new elements to insert
Replacement in Action
let colors = ['red', 'green', 'blue', 'yellow'];
// Replace 2 elements starting at index 1 with 3 new elements
colors.splice(1, 2, 'orange', 'purple', 'pink');
console.log(colors);
// ['red', 'orange', 'purple', 'pink', 'yellow']
Here, 'green' and 'blue' were removed, and three new colors took their place. The delete count and insert count don't have to match!
Think of It Like Editing Text
Imagine you're editing a sentence and want to replace "a few" with "several" — you delete the old words and type the new ones in the same spot. That's exactly what splice() does with array elements.
let scores = [10, 20, 30, 40];
scores.splice(2, 1, 99); // Replace the element at index 2
console.log(scores); // [10, 20, 99, 40]
Key Takeaway: Use splice(startIndex, deleteCount, ...newItems) to replace elements by removing and inserting in a single operation, modifying the original array.