Array Manipulation
Learn about arrays methods to increase your understanding of arrays.
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:
const shopping = ['Apple', 'Banana', 'Carrot', 'Donut', 'Eggplant'];console.log(shopping);
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:
console.log(shopping.pop());
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'
:
console.log(shopping);
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:
console.log(shopping.push('Cupcake'));
The method returns the new length of the array, which is ...