JavaScript Array Methods: Part 1

Kayla Budzeak
2 min readSep 11, 2021

This week and next I’ll be covering some fundamental array methods within JavaScript! This week will cover: .push(), .unshift(), .pop(), and .shift(). Let’s begin!

It’s important to remember that all of these methods are actually callback functions; some of which require something to be provided to it. These functions have already been defined for you within JavaScript, and so are available for you to call.

I will also try to point out which methods are “destructive”, meaning they alter the original array in place, or “non-destructive”, meaning the original array is left unaltered.

I’ll start with an array, myArray = [1,2,3]and build or destroy on it through these methods.

.push()

This method will add the element that is provided to the end of the array. On its own, it is a “destructive” method.

myArray.push(4)
//myArray === [1,2,3,4]

It can be made into a non-destructive method by using the spread operator!

newArray1 = […myArray, 5]
//newArray1 === [1,2,3,4,5]
//myArray === [1,2,3,4]

.unshift()

This method will add the provided element to the beginning of the array it’s called on; it is also destructive.

myArray.unshift(‘A’)
//myArray === [‘A’,1,2,3,4]

This one can also be turned into a non-destructive method like so:

newArray2 = [‘B’, …myArray]
//newArray2 === [‘B’,’A’,1,2,3,4]
//myArray === [‘A’,1,2,3,4]

.pop()

This method will remove and return the last element in an array destructively; it does not require an element to be provided.

myArray.pop()
//4
//myArray === [‘A’,1,2,3]

.shift()

This method will remove and return the first element in an array destructively; it does not require an element to be provided.

myArray.shift()
//’A’
//myArray === [1,2,3]

Technically both .pop() and .shift() could be made into non-destructive methods, by first creating a copy of our original array, and then calling these methods on the copy. Just be sure to keep in mind any changes made to the original array after the copy is made, will not apply to the copy.

newArray3 = [...myArray]
newArray3.pop()
//newArray3 === [1,2]
//myArray === [1,2,3]

Be sure to tune in next week for .slice(), .splice(), .filter(), and .reverse()!

--

--

Kayla Budzeak

I'm a Full-Stack Software Engineer, with a background in customer service, who recently graduated from Flatiron School. In my down time I love to bake & garden.