The JavaScript Array.shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
Syntax
arr.shift()
Return value - The removed element from the array; undefined if the array is empty.
JavaScript Array.shift() Method Examples
Example 1: Remove the first element from an array
var array1 = [1, 2, 3];
var firstElement = array1.shift();
console.log(array1);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1
Example 2: Removing an element from an array
The following code displays the myFish array before and after removing its first element. It also displays the removed element:
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
console.log('myFish before:', JSON.stringify(myFish));
var shifted = myFish.shift();
console.log('myFish after:', myFish);
console.log('Removed this element:', shifted);
Output:
myFish before: ["angel","clown","mandarin","surgeon"]
myFish after: (3) ["clown", "mandarin", "surgeon"]
Removed this element: angel
Example 3: Using shift() method in while loop
The shift() method is often used in condition inside while loop. In the following example every iteration will remove the next element from an array until it is empty:
var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"];
while( (i = names.shift()) !== undefined ) {
console.log(i);
}
// Andrew, Edward, Paul, Chris, John
Comments
Post a Comment
Leave Comment