Briefly
The shift
method removes the element at index 0 from an array and returns the value of the removed element.
Example
Let's remove the element at index 0 from the array of numbers:
const numbers = [8, 16, 32, 64]const firstItem = numbers.shift()console.log(numbers)// [16, 32, 64]console.log(firstItem)// 8
const numbers = [8, 16, 32, 64] const firstItem = numbers.shift() console.log(numbers) // [16, 32, 64] console.log(firstItem) // 8
How it works
Array
has no arguments.
Array
returns the removed element.
If the array has no elements, the method will return undefined
:
const numbers = []const firstItem = numbers.shift()console.log(firstItem)// undefined
const numbers = [] const firstItem = numbers.shift() console.log(firstItem) // undefined
How to understand
Indices are used for numbering elements in the array. The first element of the array has an index of 0.
The shift
method allows you to remove the first element from the array or, in other words, the element with index 0, shifting all the elements to the left.
More about shifting
According to the ECMAScript specification, the algorithm for the shift
method includes a loop designed to shift elements.
For clarity, let's perform the shift
method on an array-like object. For this, it is necessary for the object to have a length
field that defines the number of elements. The order of the element fields in the object does not affect the operation of the method because access to the values is carried out by index keys:
const arrayLike = { 2: 'two', 1: 'one', 0: 'zero', length: 3}console.log(arrayLike)// {'0': 'zero', '1': 'one', '2': 'two', length: 3}Array.prototype.shift.call(arrayLike)console.log(arrayLike)// {'0': 'one', '1': 'two', length: 2}
const arrayLike = { 2: 'two', 1: 'one', 0: 'zero', length: 3 } console.log(arrayLike) // {'0': 'zero', '1': 'one', '2': 'two', length: 3} Array.prototype.shift.call(arrayLike) console.log(arrayLike) // {'0': 'one', '1': 'two', length: 2}
As a result of the method execution, all remaining element fields were reassigned with new index keys and the length
field changed.
To remove the first element, the splice
method can also be used:
const colors = ['red', 'green', 'blue']colors.splice(0, 1)console.log(colors)// ['green', 'blue']
const colors = ['red', 'green', 'blue'] colors.splice(0, 1) console.log(colors) // ['green', 'blue']