Remove first element from an array in JavaScript

Let's see multiple ways to remove the first element from an array.

The first element is the element the most to the left on an array. e.g. 1 is the first element in [1, 3, 5].

Remove the first element from an array using shift (mutates array)

Explanation after the code.

const arr = [5, 6, 7];
const first = arr.shift();
console.log(first); // 5
console.log(arr); // [6, 7]

The array method shift works as follows:

  • The first item of the array is removed from the original array (changes original array)
  • The first element of the array is returned

Remove the first element from an array using slice (doesn't mutate array)

The nice thing about slice is that it doesn't change the original array. Explanation after the code.

const arr = [8, 9, 10];
const newArr = arr.slice(1);
console.log(newArr); // [9, 10]
console.log(arr); // [8, 9, 10] original unchanged

The array method slice(startIndex) works as follows:

  • The startIndex parameter is the index where to start slicing the array
  • The method returns a new array with a slice of the array without changing the original array
  • If there are no more parameters, it will slice since startIndex until the end of the array.

Remove the first element from an array using splice (mutates array)

Explanation below the code. Notice it's splice with a p, like gene splicing. Expect mutation!

const arr = [4, 5, 6];
const first = arr.splice(0, 1);
console.log(first); // [4]
console.log(arr); // [5, 6]

The array method splice(startIndex, deleteCount) works as follows:

  • The startIndex parameter is the index where to start removing elements of the array
  • The deleteCount is the number of elements to remove
  • It changes the original array
  • It returns an array with the elements removed

Performance notes

A good rule of thumb is to avoid thinking about performance if you don't have performance issues. Try to make the code readable and with minimum side effects and move on with your life.

Check this JavaScript performance and benchmarking talk.

Questions

What's the output?

const arr = [1, 2];
console.log(arr.shift(), arr);

What's the output?

const arr = [];
console.log(arr.shift());

What's the output?

const arr = [4, 8];
const res = arr.slice(1);
console.log(arr, res);

What's the output?

const arr = [];
console.log(arr.slice(1));

What's the output?

const arr = [4, 5, 6];
const res = arr.splice(0, 1);
console.log(arr, res);

What's the output?

const arr = [];
const res = arr.splice(0, 1);
console.log(arr, res);