JavaScript Array Methods

JavaScript Array Methods

Learn how and when to use push(), pop(), unshift() & shift()

Nov 1, 20212 min read

Overview

JavaScript arrays are comparably more versatile than arrays in other programming languages. That is because JavaScript arrays support dynamic memory by default which allows us to not worry about memory allocation. Furthermore, JavaScript arrays can be used as user-defined data structures like stacks and queues. In practice, what this means is that JavaScript arrays come with methods that allow us to insert and remove elements from either end of an array. In this article, we will discuss these methods and when best to use them.

Push():

The push method adds elements to the end of an array.

let sodas = ['coke'] sodas.push('sprite') // ['coke', 'sprite'] sodas.push('fanta', 'mr pibb') //['coke', 'sprite', 'fanta', 'mr pibb']

The push method also returns the new length of the array.

Pop():

The pop method removes elements from the end of an array.

let sodas = ['coke', 'sprite', 'fanta', 'mr pibb'] sodas.pop() // ['coke', 'sprite', 'fanta']

The pop method also returns the removed element. That means we can directly assign the element to another variable.

let sodas = ['coke', 'sprite', 'fanta'] let soda = sodas.pop() // 'fanta'

Unshift():

The unshift method adds an element at the beginning of an array.

let sodas = ['coke', 'sprite'] sodas.unshift('fanta') // ['fanta', 'coke', 'sprite']

The unshift methods, similar to the push method, returns the new length of the array.

Shift():

The shift method removes an element from the beginning of an array.

let sodas = ['fanta', 'coke', 'sprite'] sodas.shift() // 'fanta'

The shift method, similar to the pop method, returns the removed element from the array, and can be assigned to another variable.

When to use what?

The push and pop methods are used to add or remove elements from the end of an array respectively. The names of these methods are fairly straightforward as one pushes an element to the array and the other pops it off from the array.

The shift and unshift methods add or remove items from the front of an array respectively. These method names are not as straightforward to remember. The way I remember when to use which method is by associating the length of the method name to the length of the array. The name unshift is longer which I associate with adding an element and making the array longer. Similarly, the name shift is shorter which I associate with removing an element and making the array shorter.

In a nutshell:

JavaScript array methods push, pop, unshift and shift are used to add or remove elements from either end of the array. With the correct combination of these methods, we can use arrays as various user-defined data structures like stacks and queues. You can also get creative and use these methods according to your use case. I use this post as a cheat sheet and hope it helps you too.

Happy Coding!