Stephen Sun

Software engineer based in Houston, Texas.

I'm a detail-oriented individual who thrives in fast-paced team environments. I have experience across different industries, working with both front end and back end technologies.

How to add or remove an element at the beginning of an array

Using the push() method, we can add elements to the end of an array.

But what if our goal is to add elements to the beginning of an array?

JavaScript has another method called unshift() that can do just that.

Let's say we have an array of colors:

const colors = ['red', 'blue', 'green']

And we want to add the color yellow to the beginning of our array:

console.log(colors.unshift('yellow')) // 4
console.log(colors) // ['yellow', 'red', 'blue', 'green']

We can also add more than one color at a time.

Let's take our colors array (including yellow) and add some more colors:

console.log(colors.unshift('orange', 'gray', 'black')) // 7
console.log(colors) // ['orange', 'gray', 'black', 'yellow', 'red', 'blue', 'green]

What if we want to remove an element from the beginning of the array instead?

Similar to the pop() method which removes the last element of an array, we have the shift() method!

Let's take our colors array that now has seven colors and remove the first element:

console.log(colors.shift()) // orange
console.log(colors) // ['gray', 'black', 'yellow', 'red', 'blue', 'green]

If we want to remove multiple colors, then we would need to use the shift() method in a loop.

The downside to using unshift() and shift() is that these methods mutate the original array.

If we want to avoid mutations, we can use concat() or the spread operator, which will return a new array.