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
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.
const fruits = ["apple", "banana", "cherry"];
const firstElement = fruits.shift();
console.log(firstElement); // Output: "apple"
console.log(fruits); // Output: ["banana", "cherry"]
Output
apple
[ 'banana', 'cherry' ]
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
.
const emptyArray = [];
const result = emptyArray.shift();
console.log(result); // Output: undefined
console.log(emptyArray); // Output: []
Output
undefined
[]
emptyArray.shift()
returnsundefined
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.
const numbers = [1, 2, 3, 4];
while (numbers.length > 0) {
console.log(numbers.shift());
}
console.log(numbers); // Output: []
Output
1
2
3
4
[]
- 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.
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' ]
- The first element,
"first"
, is removed usingshift()
. "fourth"
is added to the end of the array usingpush()
.