Remove the First and Last Array Elements in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 06 20212 min read

Remove the First and Last Array Elements #

To remove the first and last elements from an array, call the shift() and pop() methods on the Array. The shift method removes the first and the pop method removes the last element from an array. Both methods return the removed elements.

index.js
const arr = ['a', 'b', 'c', 'd']; const removeFirst = arr.shift(); console.log(removeFirst); // ๐Ÿ‘‰๏ธ a const removeLast = arr.pop(); console.log(removeLast); // ๐Ÿ‘‰๏ธ d console.log(arr) // ๐Ÿ‘‰๏ธ ['b', 'c']

In the code snippet we've used the Array.shift and Array.pop methods to remove the first and last elements from the array.

These methods mutate the original array.

If you call the shift and pop methods on an empty array, they would not throw an error.

index.js
const arr = []; const removeFirst = arr.shift(); console.log(removeFirst); // ๐Ÿ‘‰๏ธ undefined const removeLast = arr.pop(); console.log(removeLast); // ๐Ÿ‘‰๏ธ undefined console.log(arr); // ๐Ÿ‘‰๏ธ []
Most experienced developers avoid using methods that mutate objects and arrays. This behavior is difficult to debug and reason about.
Most of the time, a better approach is to create a copy of the array, containing only the elements we need.

To create a copy of the original array, that contains only the elements we need, use the Array.slice method. This method does not change the contents of the original array.

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

In the code snippet we pass the following parameters to the Array.slice method:

  • start index - index (zero-based) at which to start extraction. In the example, we start at the second element (index 1)
  • end index - extract values up to, but not including this index. A negative index indicates an offset from the end of the array.

A negative index of -1 means go up to, but not including the last element of the array.

The advantage of using the slice method is that the original array remains unchanged and we don't have to think about how the array's values change over time in our code.

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