...

/

Array Manipulation

Array Manipulation

Learn about arrays methods to increase your understanding of arrays.

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:

Press + to interact
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.

Press + to interact
Popping the last item out of the array
Popping the last item out of the array

The code below shows how the method is applied to the shopping array:

Press + to interact
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' :

Press + to interact
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.

Press + to interact
A cupcake pushed onto the end
A cupcake pushed onto the end

We would use the following code to do this:

Press + to interact
console.log(shopping.push('Cupcake'));

The method returns the new length of the array, which is ...