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:

array.shift()

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 index 0, and so on).

Example 1: Removing the first element

let fruits = ['apple', 'banana', 'orange']; let removedFruit = fruits.shift(); console.log(fruits); // ['banana', 'orange'] console.log(removedFruit); // 'apple' (the removed element)

Example 2: Using shift() on an empty array

let emptyArray = []; let result = emptyArray.shift(); console.log(result); // undefined

Example 3: Using shift() in a loop

let numbers = [1, 2, 3, 4]; while (numbers.length > 0) { console.log(numbers.shift()); // prints 1, 2, 3, 4 (in this order) } console.log(numbers); // []

Performance Consideration:

  • Time complexity: The time complexity of shift() is O(n), where n 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 like pop() (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 returns undefined. Keep in mind that shift() is less efficient than pop() for large arrays because it requires re-indexing the remaining elements.