How to Use splice in JavaScript: Syntax and Examples
The
splice() method in JavaScript changes an array by removing, replacing, or adding elements at a specified index. You call it on an array with the start index, number of elements to remove, and optional new elements to insert.Syntax
The splice() method has this syntax:
array.splice(start, deleteCount, item1, item2, ...)
start: The index where changes begin.
deleteCount: How many elements to remove from start.
item1, item2, ...: Optional elements to add starting at start.
javascript
array.splice(start, deleteCount, item1, item2, ...);
Example
This example shows how to remove and add elements using splice():
javascript
const fruits = ['Apple', 'Banana', 'Cherry', 'Date']; // Remove 1 element at index 1 (Banana) const removed = fruits.splice(1, 1); // Add 'Blueberry' and 'Blackberry' at index 1 fruits.splice(1, 0, 'Blueberry', 'Blackberry'); console.log('Removed:', removed); console.log('Updated array:', fruits);
Output
Removed: [ 'Banana' ]
Updated array: [ 'Apple', 'Blueberry', 'Blackberry', 'Cherry', 'Date' ]
Common Pitfalls
Common mistakes when using splice() include:
- Forgetting that
splice()modifies the original array. - Using a
deleteCountlarger than the remaining elements, which just removes until the end. - Confusing
splice()withslice(), which does not change the original array.
javascript
const arr = [1, 2, 3, 4]; // Wrong: expecting slice behavior const wrong = arr.splice(1, 2); console.log('After splice:', arr); // arr is changed // Right: use slice to copy without changing const right = [1, 2, 3, 4].slice(1, 3); console.log('After slice:', right);
Output
After splice: [ 1, 4 ]
After slice: [ 2, 3 ]
Quick Reference
| Parameter | Description |
|---|---|
| start | Index to start changing the array |
| deleteCount | Number of elements to remove from start |
| item1, item2, ... | Elements to add starting at start (optional) |
Key Takeaways
Use
splice() to add, remove, or replace elements in an array at any position.splice() changes the original array and returns the removed elements as a new array.The first argument is the start index, the second is how many elements to remove, followed by optional elements to add.
Be careful not to confuse
splice() with slice(), which does not modify the original array.If
deleteCount is 0, splice() only inserts elements without removing any.