What You'll Learn
You'll learn how to use splice() to delete one or more elements from any position in an array, modifying the original array and optionally retrieving the removed items.
Removing Elements with splice()
While you've already seen that splice() is the Swiss Army knife of array methods, its most common use is removing elements from specific positions. The basic syntax for deletion is:
array.splice(startIndex, deleteCount)
The startIndex tells splice() where to begin, and deleteCount specifies how many elements to remove from that point forward.
Removing a Single Element
let fruits = ['apple', 'banana', 'cherry', 'date'];
fruits.splice(1, 1); // Remove 1 element starting at index 1
console.log(fruits); // ['apple', 'cherry', 'date']
Removing Multiple Elements
let numbers = [10, 20, 30, 40, 50];
numbers.splice(1, 3); // Remove 3 elements starting at index 1
console.log(numbers); // [10, 50]
The Return Value
splice() returns an array containing the removed elements, which is useful if you need to process or store what was deleted:
let colors = ['red', 'green', 'blue', 'yellow'];
let removed = colors.splice(2, 2);
console.log(removed); // ['blue', 'yellow']
console.log(colors); // ['red', 'green']
Think of It Like Surgery
Imagine splice() as a surgical tool that cuts out a section of the array. You tell it where to start cutting and how many items to remove, and it hands you back what was cut out while the original array heals shut.
Key Takeaway: Use splice(startIndex, deleteCount) to remove one or more elements from any position in an array; it mutates the original array and returns the deleted elements.