All About Splice() Method In Javascript

All About Splice() Method In Javascript

Table of contents

No heading

No headings in the article.

The Splice() methods is one of the array methods which is used to add, remove or replaces the content of an array. This method mutates the original array unlike Slice() method. It accepts total of three parameters.

1. start : This parameter indicate the index at which operation on array can be performed.

let arr=["a","b","c","d","e"]
let removedItems=arr.splice(2)
console.log(removedItems) //["c", "d", "e"]
console.log(arr) //["a", "b"]

From the above code we can deduce that the removedItems stored the array elements which are removed from original array. If the index is negative, let's say -1 then start parameter points to the last element of an array.

let arr=["a","b","c","d","e"]
let removedItems=arr.splice(-2)
console.log(removedItems) //[ "d", "e"]
console.log(arr) //["a", "b","c"]

Here, -2 points to the element "d" so splice method operation starts at index -2 and will end until it does not reach the last element of an array which is at index -1. Both of the elements "d" and "e" removed from original array.

2. deleteCount (Optional): This parameter indicate the number of elements to be deleted from the start index. If deleteCount is zero or negative, no elements are deleted. If deleteCount is equal or greater than array length then, elements from the start index to the last element of an array are removed.

let arr=["a","b","c","d","e"]
let removedItems=arr.splice(2,3)
console.log(removedItems) //["c", "d", "e"]
console.log(arr) //["a", "b"]

In this splice method removed the 3 elements from the start index and left the original array with the elements "a" and "b" .

a. If index is negative:

let arr=["a","b","c","d","e"]
let removedItems=arr.splice(2,-1)
console.log(removedItems) //[] (No elements are removed)
console.log(arr) //["a", "b", "c", "d", "e"]

b. If index is equal or greater than array length:

let arr=["a","b","c","d","e"]
let removedItems=arr.splice(2,7)
console.log(removedItems) //["c", "d", "e"] 
console.log(arr)  //["a", "b"]

In this deleteCount is greater then the array length so elements from start index to array length are removed

3. elementsToAdd (Optional): This parameters add the elements from the start index.

let arr=["a","b","c","d","e"]
let removedItems=arr.splice(2,3,"f")
console.log(removedItems) // ["c", "d", "e"]
console.log(arr) // ["a", "b", "f"]

In the splice method removed the 3 elements from start index and insert element "f".

Combined examples: Untitled (23).jpg