splice()

ES3+

Changes the contents of an array by removing or replacing existing elements and/or adding new elements.

Syntax

array.splice(start, deleteCount, item1, item2, ...)

Parameters

start number

Index at which to start changing the array

deleteCount number optional

Number of elements to remove

Return Value

Array

An array containing the deleted elements

Examples

JavaScript
const fruits = ['apple', 'banana', 'cherry'];
fruits.splice(1, 1, 'blueberry', 'blackberry');
console.log(fruits);
Output:
// ['apple', 'blueberry', 'blackberry', 'cherry']

📌 When to Use

Use splice() when you need to modify an array in place - removing elements, inserting new ones, or replacing existing elements. It's the Swiss Army knife for array mutation at specific positions.

⚠️ Common Mistakes

Confusing splice() with slice() - splice() modifies the original array

Forgetting that splice() returns the removed elements, not the modified array

Using splice() in React/Vue state directly - this mutates state and won't trigger re-renders properly

✅ Best Practices

For immutable operations, use slice() and spread instead: [...arr.slice(0, i), ...arr.slice(i+1)]

To insert without removing: arr.splice(index, 0, newItem)

Use negative start index to work from the end: arr.splice(-1, 1) removes last item

⚡ Performance Notes

splice() is O(n) because elements after the splice point must be shifted. For frequent insertions/deletions at arbitrary positions in large arrays, consider using a linked list data structure instead.

🌍 Real World Example

Managing a Todo List

Insert, remove, and reorder items in a todo list

const todos = [
  {id: 1, text: 'Learn JavaScript'},
  {id: 2, text: 'Build a project'},
  {id: 3, text: 'Deploy to production'}
];

// Insert at position 1
todos.splice(1, 0, {id: 4, text: 'Practice arrays'});

// Remove item at position 2
const [removed] = todos.splice(2, 1);

// Replace item at position 0
todos.splice(0, 1, {id: 5, text: 'Master JavaScript'});

Related Methods