Remove the first Element from an Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Remove the first Element from an Array #

Use the Array.shift() method to remove the first element from an array, e.g. const firstElement = arr.shift();. The shift method removes the first element from an array and returns the removed element.

index.js
const arr = ['a', 'b', 'c']; const firstElement = arr.shift(); console.log(firstElement); // 👉️ a console.log(arr); // 👉️ ['b', 'c']

We used the Array.shift method to remove the first element from the array.

The Array.shift method mutates the original array and changes its length.

The shift method removes the array element at index 0.

If you call the Array.shift method on an empty array, the method returns undefined.

index.js
const arr = []; const firstElement = arr.shift(); console.log(firstElement); // 👉️ undefined console.log(arr); // 👉️ []
In my experience mutating arrays and objects is difficult to track throughout a codebase, especially if you have to perform other operations on the array after mutating it.

An alternative is to create a copy of the array starting with the second element.

Use the array.slice() method to remove the first element from an array, e.g. const withoutFirst = arr.slice(1);. The slice() method will return a shallow copy of the original array starting with the second element.

index.js
const arr = ['a', 'b', 'c']; const withoutFirst = arr.slice(1); console.log(withoutFirst); // 👉️ ['b', 'c'] console.log(arr); // 👉️ ['a', 'b', 'c']

We passed a starting index of 1 and no end index to the Array.slice method.

The method returns a shallow copy of the original array containing the elements from index 1 onwards.

The Array.slice method is very different from Array.shift because it doesn't change the contents of the original array.

This is my recommended approach because once you start mutating the same array at multiple places, things get very confusing and difficult to track.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.