The splice method of JavaScript

The splice method of the arrays is used to add new elements or remove existing elements from an array. The JS splice method also returns an array of removed elements.

An example of splice method

Look carefully at the syntax of splice method that takes two important parameters along with others.

Syntax of array splice method

Following is the general syntax of JavaScript array splice method:

Arrayname.splice (Number index, howMany Number, element1, ….);

Where:

  • Number index specifies where splice method should start adding new elements. It will remove any existing elements from that index number in the array.
  • howMany: parameter of array splice method specifies how many elements to add.
  • element1,..: these are the new elements to be added into the array.

See example below to learn more about how to use splice JavaScript method.

An example of using JavaScript splice method

Following is an example of using the splice method. We have created a numeric array of four elements (1,2,3,4). We will display array elements by using the for loop.

After that, array splice method will be used to add two more elements from index number 3. After using the splice method, the array will be displayed again, so you can see the difference. See the demo example by clicking the link or image below:

Experience this example online

You can see, NumArr is displayed before and after using array splice method. The splice method removed the 4th element (index = 3) and added two more elements at the end.

Splice method with return value example

Following example shows the returned array after array splice method is used. We are using the same example as above except we will assign the return array while using splice method.

The alert will show the returned array element values. While HTML paragraphs will show array before and after the splice method. See the example by clicking the link below:

Experience this example online

You can see, array splice removed the fourth element which index is 3. The returned array is assigned to another array which is shown by alert (as the example page loads). You can see the new array shows ‘4’ while spliced array does not show it in the paragraph.

Note that, if you only provide index number in array splice method it will simply remove array elements from that index number. While returned array would have all removed elements. See below:

Experience this example online

You can see, splice removed elements from the given index. The new array contains all removed elements that are shown in an alert. While array that used JavaScript splice left with only one element.