Course contentsShow
← JavaScript
Lesson 813 of 2,72319. ArraysFree lesson

splice(): The Swiss Army Knife Method

Master splice() to add, remove, or replace elements at any position in an array.

splice(): The Swiss Army Knife Method

You'll learn how splice() can add, remove, or replace elements at any position in an array — all in one powerful method.

The Core Idea

While push(), pop(), shift(), and unshift() work only at the ends of an array, splice() lets you modify an array anywhere. Think of it like a word processor's "find and replace" feature — but for array elements. You can cut out a section, insert new items, or do both at once.

How splice() Works

The syntax is: array.splice(startIndex, deleteCount, item1, item2, ...)

  • startIndex: Where to begin the operation
  • deleteCount: How many elements to remove (0 means "don't remove any")
  • item1, item2, ...: Optional items to insert at that position
let fruits = ['apple', 'banana', 'cherry', 'date'];

// Remove 2 elements starting at index 1
fruits.splice(1, 2);
console.log(fruits); // ['apple', 'date']

fruits = ['apple', 'banana', 'cherry', 'date'];

// Remove 1, then insert 2 new elements at index 1
fruits.splice(1, 1, 'blueberry', 'blackberry');
console.log(fruits); // ['apple', 'blueberry', 'blackberry', 'cherry', 'date']

fruits = ['apple', 'banana', 'cherry'];

// Insert without removing (deleteCount = 0)
fruits.splice(1, 0, 'apricot');
console.log(fruits); // ['apple', 'apricot', 'banana', 'cherry']

Return Value

splice() returns an array containing the removed elements. If nothing was removed, it returns an empty array.

let colors = ['red', 'green', 'blue', 'yellow'];
let removed = colors.splice(1, 2);
console.log(removed); // ['green', 'blue']
console.log(colors);  // ['red', 'yellow']

Key Takeaway: splice() is the go-to method when you need surgical precision — it mutates the array by adding, removing, or replacing elements at any index, and returns what was removed.