Array methods - push, pop, shift and unshift
As we could access the length
property of an array, we can also access functions built into the array to manipulate it. These functions are called methods
.
In this lesson, we will learn about the push
, pop
, shift
and unshift
methods.
push
The push
method adds an element to the end of an array.
pop
The pop
method removes the last element of an array.
shift
The shift
method removes the first element of an array.
unshift
The unshift
method adds an element to the beginning of an array.
There are other methods that can be used to manipulate arrays. You'll learn about them in the next sections.
Caution
The shift
and unshift
methods are slower than push
and pop
. As they modify the beginning of the array, they have to move all the other elements in the array to a new place in memory.
Exercise
Do you remember what each method does? Select the correct method for each description.
Add an element to the end of an array.
Remove an element from the end of an array.
Remove an element from the beginning of an array.
Add an element to the beginning of an array.