Array.shift()

The Array.shift() method in JavaScript removes the first element from an array and returns that element. This method modifies the original array by reducing its length by one.

Syntax

</>
Copy
array.shift()

Parameters

The shift() method does not take any parameters.

Return Value

The shift() method returns the first element that was removed from the array. If the array is empty, it returns undefined.


Examples

1. Removing the First Element from an Array

This example demonstrates removing the first element of an array using shift(). The array is modified, and the removed element is returned.

</>
Copy
const fruits = ["apple", "banana", "cherry"];

const firstElement = fruits.shift();
console.log(firstElement); // Output: "apple"
console.log(fruits); // Output: ["banana", "cherry"]

Output

apple
[ 'banana', 'cherry' ]
  1. fruits.shift() removes the first element, "apple", and modifies the array to contain the remaining elements.

2. Using shift() on an Empty Array

When shift() is used on an empty array, it returns undefined.

</>
Copy
const emptyArray = [];

const result = emptyArray.shift();
console.log(result); // Output: undefined
console.log(emptyArray); // Output: []

Output

undefined
[]
  1. emptyArray.shift() returns undefined since the array is empty, and the array remains unchanged.

3. Using shift() in a Loop

The shift() method can be used to remove elements from an array one at a time in a loop until the array is empty.

</>
Copy
const numbers = [1, 2, 3, 4];

while (numbers.length > 0) {
    console.log(numbers.shift());
}

console.log(numbers); // Output: []

Output

1
2
3
4
[]
  1. The loop continues until the array is empty, with shift() removing the first element in each iteration.

4. Combining shift() with Other Array Methods

The shift() method can be combined with other array methods like push() or concat() for custom operations.

</>
Copy
const queue = ["first", "second", "third"];

// Remove the first element
const served = queue.shift();

// Add a new element to the queue
queue.push("fourth");

console.log(served); // Output: "first"
console.log(queue); // Output: ["second", "third", "fourth"]

Output

first
[ 'second', 'third', 'fourth' ]
  1. The first element, "first", is removed using shift().
  2. "fourth" is added to the end of the array using push().