It’s Festive Season! Enjoy 30% Off

Use code FESTIVE30 at checkout

Code has been added to clipboard!

splice

Reading time 2 min
Published Aug 10, 2017
Updated Oct 10, 2019

JavaScript splice: Main Tips

  • The JavaScript splice() method adds or removes items from an array.
  • The original array gets changed by this method.
  • The array.splice JavaScript method an array of the removed items.

Learn Syntax of splice

Here you can see the basic syntax for this JavaScript splice() function:

array.splice(index, howmany, item1, item2...)

The array.splice JavaScript function accepts several parameters in the parentheses. First of all, you have to indicate the index, or the position in which the removal (or addition process) is supposed to begin.

Secondly, you can include an optional parameter called howmany which specifies the number of elements to be eliminated from the array. Parameter is the item which indicates the elements to be added to the array.

Parameter Description
index Required. Defines the position to add or remove elements.
Negative values will count the position from the end of the array.
howmany Not required. Sets the number of items to remove.
0 means nothing will be removed.
item1, item2... Not required. Specifies the items to add.
Example
var pets = ["Cat", "Mouse", "Rat", "Cactus"];
pets.splice(2, 2, "Llama", "Horse");

Using splice

No wonder JavaScript splice() function is considered to be perfectly-suited for array management. The invoked method will help you change the content of arrays: you can either add new elements or remove the ones that are no longer necessary.

Unlike other JavaScript functions that do not affect the original arrays (for example, Javascript slice()), the JS splice() removes or adds elements directly from or to them. However, the method also generates a list of elements that were deleted from the array. If you chose only to add items, the presented array would be empty.