Remove the First and Last Array Elements in JavaScript

In this tutorial, you will learn about how to remove the first and last element from an array in JavaScript.

In Javascript to remove the first and last element from an array, we can use the shift() and pop() methods. The shift method removes the first and the pop method removes the last element from an array. Both methods return the removed elements.

const arr = ['javascript', 'jquery', 'vue', 'react'];

const removeFirst = arr.shift();
console.log(removeFirst); // javascript

const removeLast = arr.pop();
console.log(removeLast); // react

console.log(arr) // ['jquery', 'vue']

Similarly, we can also use the slice() method by passing 1, -1 as an arguments, slicing starts from index 1 and ends before the last index (-1 represents the last element index).

const arr = ['javascript', 'jquery', 'vue', 'react'];

const withoutFirstAndLast = arr.slice(1, -1);
console.log(withoutFirstAndLast); // ['jquery', 'vue']

console.log(arr) // ['javascript', 'jquery', 'vue', 'react']

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.

Note: The slice() method doesn’t modify the original array instead of it returns the new array with the sliced elements.