The shift() method in JavaScript is used to remove the first element from an array and returns that removed element. This method changes the length of the array.
Syntax
array.shift();
Return Value
Return Type | Description |
---|---|
Any | The element that was removed from the array. |
Example 1: Removing the First Element
This code demonstrates how to use the shift() method to remove the first element from an array.
let Arr = [ 10, 20, 30, 40, 50 ]; let removedItem = Arr.shift(); console.log('Removed Element:', removedItem); console.log('Array After Shift:', Arr);
Output:
Removed Element: 10
Array After Shift: [ 20, 30, 40, 50 ]
Example 2: Removing the First Element from an Empty Array
If the array is empty, shift()
returns undefined
.
let Arr = []; let removedItem = Arr.shift(); console.log('Removed Element:', removedItem); console.log('Array After Shift:', Arr);
Output:
Removed Element: undefined
Array After Shift: []
Note:
The shift()
method changes the original array and does not create a new array. It updates the indexes of the remaining elements in the array.
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 4 | 1 |