How to use the splice() method in JavaScript
The JavaScript splice() method changes the elements of the array by replacing or removing the elements, in place.
Note: As compared to the
slice()method which does not change the original array,splice()method changes are reflected in the original array.
Syntax
The syntax is as follows:
Removed: The array which stores all the removed elements that thesplice()method returnsArray: The array on whichsplice()method is being appliedSplice: Function call to the methodIndex: Starting index for thesplice()methodCount: Specifies the number of items in the array to replace/remove from the startingindexItems: Items that replace the array elements from the startingindex
Optional Arguments:
Countanditemsarguments are optional in the function call.
Examples
Given below are some examples that show multiple ways to use the splice() method.
1. Remove all elements following the first element
var arr = ['A', 'B', 'C', 'D'];var removed = arr.splice(1, arr.length-1);console.log('Original Array: ', arr)console.log('Removed Elements: ', removed)// arr is ['A']// removed is ['B', 'C', 'D']
2. Replace all elements following the first element
var arr = ['A', 'B', 'C', 'D'];var removed = arr.splice(1, arr.length-1, 'X', 'Y', 'Z');console.log('Original Array: ', arr)console.log('Removed Elements: ', removed)// arr is ['A', 'X', 'Y', 'Z']// removed is ['B', 'C', 'D']
3. Remove 0 (zero) elements and insert 2 elements at index 2
var arr = ['A', 'B', 'C', 'D'];var removed = arr.splice(2, 0, 'X', 'Y');console.log('Original Array: ', arr)console.log('Removed Elements: ', removed)// arr is ['A', 'B', 'X', 'Y', 'C', 'D']// removed is []
4. Remove all elements following a specified index
var arr = ['A', 'B', 'C', 'D', 'E', 'F'];index = 3var removed = arr.splice(index);console.log('Original Array: ', arr)console.log('Removed Elements: ', removed)// arr is ['A', 'B', 'C']// removed is ['D', 'E', 'F']
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved