Array Manipulation
Explore how to manipulate arrays in JavaScript using methods like pop, push, shift, and unshift to add or remove elements. Understand the spread operator to merge arrays and insert items dynamically. This lesson equips you with essential array manipulation techniques for practical coding.
We'll cover the following...
Popping and pushing
Arrays have methods called pop and push that can be used to remove or add
items.
The pop() method removes the last item from an array. To see it in action,
let’s create a new shopping list array:
We can remove the last item in the array using the pop() method, which will
“pop” the last item out of the array, as shown in the diagram below.
The code below shows how the method is applied to the shopping array:
The method returns the last item of the array and also updates the array so
that it no longer contains the item. If we take a look at the shopping array,
we’ll see that it no longer contains the string 'Eggplant' :
If we instead want to add a new value to the end of an array, we can use the
push() method. For example, it can be used to add a cupcake to the end of
the shopping array, as illustrated in the diagram below.
We would use the following code to do this:
The method returns the new length of the array, which is ...