Remove the first Element from an Array in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 06 20212 min read

Remove the first Element from an Array #

To remove the first element from an array, call the shift method on the array, e.g. 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']

In the code snippet 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 element at index 0 of the array.

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 (changing) the structure of arrays and objects is very difficult to debug and reason about, especially if you have to perform other operations on the array after mutating it.

An alternative is to create a copy of the array containing all the elements, but the first.

We can use the Array.slice method to get a new array, containing all array elements, but the first.

index.js
const arr = ['a', 'b', 'c']; const withoutFirst = arr.slice(1); console.log(withoutFirst); // ๐Ÿ‘‰๏ธ ['b', 'c'] console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c']

In the code snippet we pass a starting index of 1 and no end index to the Array.slice method.

The method returns a shallow copy of the original array with all elements starting at index 1.

The Array.slice method is very different from Array.shift, because it does not change the contents of the original array.

This is my recommended approach, because once you start mutating the same array with multiple operations, things get very confusing and we are forced to think about multiple operations at the same time.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee