6.6 Deleting Elements in an Array
Let's see now how to remove elements from an array. So, start by declaring a new array, numbers, and we set it to 1, 2, 3, 4. Earlier in this section, you learned about 3 methods to add new elements to an array. You learned about the push method, which we use to add something to the end of an array. You learned about the unshift method, which we use to add elements to the beginning of an array and the splice method, which we use to add an element somewhere in the middle. Now, when it comes to deleting an element, again, we can delete an element from the end, the beginning and the middle. Middle. But instead of the push method, we use the pop method. That will delete the last element of this array and return it. So let's store that in a constant called last. And here I'm going to do a console. Log of numbers, so you can see the array after you delete this last element. Save the changes. So here's our array, 1, 2, 3, and you can see that the last element is 4. Now if you want to delete an element from the beginning, you use the shift method. Similar to the pop method, this will return the element that was deleted. So we can store this first, and let's take a look here, let's save the changes. So the first element is 1, now if we save numbers, we only have 2 and 3. So it's pretty simple. And finally we have the splice method that you learned earlier, so if you want to delete an element somewhere in the middle, you pass the index of that element. So let's say we want to delete this 3 here. The index of this element is 2, so we pass 2 here, and as a second argument, we pass the number of elements we want to delete. We can delete 1 element, then let's save this to the console, let's save the changes, I'll comment out these two lines so that we're working with our original array, let's take a look, the 3 has been deleted we have 1, 2 and 4. Now if you want to delete multiple items, you pass a value greater than 1. So you can delete 2 items, starting with index 2. Save the changes, so 3 and 4 are deleted and we only have 1 and 2. So to recap, use the pop method to delete the last element, use the shift method to delete the first element and the splice element to delete an element somewhere in the middle of an array. That's it for this video on deleting elements in an array in JavaScript, let's get together for a very next video.