Mon Oct 11 2021·3 min read
Photo by Christopher Machicoane
splice() method to add an element into an array at a specific index.
The method changes the contents of an array by removing, replacing or adding new
elements, starting at a supplied index.
const arr = ['a', 'c']; arr.splice(1, 0, 'b'); // 👇️ ['a', 'b', 'c'] console.log(arr);
The parameters we pass to the Array.splice method are:
0and the last an index of
arr.length - 1.
What might seem confusing to you is:
"Why are we providing a delete count parameter when adding an element to the array?".
splice method is used to do 3 very different things.
Here's the same example, using named variables to make this a little more readable.
const arr = ['a', 'c']; const startIndex = 1; const deleteCount = 0; const elementToInsert = 'b'; arr.splice(startIndex, deleteCount, elementToInsert); // 👇️ ['a', 'b', 'c'] console.log(arr);
We start changing the array at index
0 elements and add an element
with the value of
b at the start index (
splicemethod returns an array containing the deleted elements, however because we set the second parameter (delete count) to
0it would return an empty array.
We can also insert more than 1 element, starting at the supplied index.
const arr = ['a']; arr.splice(1, 0, 'b', 'c'); // 👇️ ['a', 'b', 'c'] console.log(arr);
In this example we add the elements with values
c in the array,
starting at index
The elements will be added in the order they were provided to the
b will be at index
c will be at index
If you have an array containing the elements you want to add starting at the specified index, you can use the spread operator (...).
const arr = ['a']; const elements = ['b', 'c']; arr.splice(1, 0, ...elements); // 👇️ ['a', 'b', 'c'] console.log(arr);
An easy way to think about the
spread operator (...)
is that we are unpacking the values from the array and passing them as multiple
comma-separated arguments to the
I couldn't tell you why they thought it would be a good idea to use the same method to replace, remove and add elements to an array.
splicemethod it takes you a couple of seconds to remember the order of the parameters and to determine how it is used. Are we adding / removing or replacing elements here.
I'll send you 1 email a week with links to all of the articles I've written that week