The JavaScript Array.shift() method removes the first element from an array and returns that element. This method modifies the original array, reducing its length by one, and shifts all the other elements to lower indexes.
For example, array.shift() is useful when you need to remove and retrieve the first element from an array, especially in queue-like operations.
Syntax
The syntax for the Array.shift() method is:
array.shift()
Parameters
The Array.shift() method does not accept any parameters.
Return Value
The method returns the removed first element from the array.
If the array is empty, it returns undefined.
Examples of JavaScript Array.shift() Method
Example 1: Removing the First Element of an Array
The shift() method removes and returns the first element of the array.
const fruits = ['apple', 'banana', 'mango'];
const firstFruit = fruits.shift();
console.log(firstFruit); // Output: "apple"
console.log(fruits); // Output: ['banana', 'mango']
Explanation: The shift() method removes 'apple', the first element in the fruits array, and returns it. The remaining array is now ['banana', 'mango'].
Example 2: Using shift() on an Empty Array
If the shift() method is called on an empty array, it returns undefined.
const emptyArray = [];
const result = emptyArray.shift();
console.log(result); // Output: undefined
console.log(emptyArray); // Output: []
Explanation: Since the array is empty, the shift() method returns undefined and does not modify the array.
Example 3: Modifying the Length of an Array with shift()
The shift() method reduces the length of the array by removing the first element.
const numbers = [10, 20, 30, 40];
numbers.shift();
console.log(numbers.length); // Output: 3
Explanation: After removing the first element (10), the length of the numbers array is reduced from 4 to 3.
Example 4: Using shift() on an Array of Objects
The shift() method works with arrays containing objects, removing the first object from the array.
const users = [{ name: 'Alice' }, { name: 'Bob' }, { name: 'Charlie' }];
const firstUser = users.shift();
console.log(firstUser); // Output: { name: 'Alice' }
console.log(users); // Output: [{ name: 'Bob' }, { name: 'Charlie' }]
Explanation: The shift() method removes the first object ({ name: 'Alice' }) from the users array and returns it.
Example 5: Combining shift() with Other Array Methods
You can combine shift() with other array methods like push() or pop() to implement queue-like structures.
const queue = ['first', 'second', 'third'];
queue.shift();
queue.push('fourth');
console.log(queue); // Output: ['second', 'third', 'fourth']
Explanation: The shift() method removes the first element ('first'), and push() adds 'fourth' to the end of the array, simulating a queue operation.