JavaScript shift() method
The shift()
method in JavaScript is used to remove the first element from an array. It modifies the original array by removing the element at index 0
and returns the removed element. If the array is empty, shift()
returns undefined
.
Syntax:
Return Value:
- The removed element from the array.
- If the array is empty, it returns
undefined
.
Key Points:
- Modifies the original array: The
shift()
method alters the array by removing the first element. - Returns the removed element: The removed element is returned by the method.
- Shifts the remaining elements: After removing the first element, all remaining elements in the array are "shifted" to lower indices (i.e., index
1
becomes index0
, and so on).
Example 1: Removing the first element
Example 2: Using shift()
on an empty array
Example 3: Using shift()
in a loop
Performance Consideration:
- Time complexity: The time complexity of
shift()
is O(n), wheren
is the number of elements in the array. This is because after removing the first element, all other elements have to be re-indexed (shifted) by one position, which makes it less efficient for large arrays compared to methods likepop()
(which operates on the last element).
Summary:
shift()
removes the first element from an array and returns it. The remaining elements are shifted down by one index, and the array is modified. If the array is empty, it returnsundefined
. Keep in mind thatshift()
is less efficient thanpop()
for large arrays because it requires re-indexing the remaining elements.