Output
In the above example, the output of will be [2, 3]
and the output of will be 1
.
Explanation
The shift()
method works by removing the first element from the array and then shifting all the remaining elements down by one index. The first element is then returned. If the array is empty or undefined, the shift()
method will return undefined
.
Use
The shift()
method can be used to remove the first element of an array. This is useful when you only need to access the first element and want to remove it immediately. It is also useful when you are iterating over an array and want to remove elements one by one from the beginning.
Important Points
- The
shift()
method modifies the original array and returns the shifted element.
- If the array is empty,
shift()
returns undefined
.
- The
shift()
method is the opposite of the push()
method which adds elements to the end of an array.
Summary
The shift()
method in JavaScript removes the first element of an array and returns it. It can be useful for situations where you only need to access the first element, or when iterating over the array and removing elements one by one from the beginning. However, it does modify the original array, so caution should be taken when using it.