Borislav Hadzhiev
Wed Oct 06 2021·2 min read
Photo by John Mark Arnold
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.
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.
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
.
const arr = []; const firstElement = arr.shift(); console.log(firstElement); // 👉️ undefined console.log(arr); // 👉️ []
We can use the Array.slice
method to get a new array, containing all array
elements, but the first.
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.