FreeCodeCamp and JavaScript: The splice() Method

Today we are going to look at the splice() method in JavaScript.  The splice() method can remove an existing element(s) from anywhere in an array and / or insert a new element(s) into an array, and it can insert a new element anywhere you specify in the array, which makes it different from push() and pop().

Here, per MDN, is the syntax:

array.splice(start, deleteCount[, item1[, item2[, …]]])

That looks a little complicated, so let’s break it down as usual.  array is, of course the array that we’re processing.  In the parameters, we have start, which is the element to start the splice at.  As always, 0 is the first element in the array, so keep that in mind if that’s where you want to begin.  If you give a negative value, the splice will begin that many elements from the end of the array, e.g., -2 means it starts two elements back from the end of the array.

deleteCount tells the splice() function how many items to remove.  If you put 0, nothing will be removed, which is kind of pointless, so be sure to at least put a 1 (unless you’re just inserting an element).  If you goof and put more than the length of the array, it will delete everything through to the end of the array.  Finally, if you leaved off this value, it will take the length of the array minus your start value and delete that many elements.

Next are optional elements.  These will be added to the array, beginning at your start index.  Obviously, if you don’t list anything to be added, all the splice() function will do is delete items from the array.

The splice() function will return an array that has the items you DELETED. It will be an empty array if you didn’t delete anything. Also, if you added more elements than you deleted, the length of the original array will change.

So, let’s look at MDN’s example.

We have an array:

var myFish = [‘angel’, ‘clown’, ‘mandarin’, ‘surgeon’];

Now, let’s perform some splice() operations on it.