JavaScript Array shift() method is used to remove the first element from the array and returns that removed element. It modifies the original array.
Syntax
array.shift()
Parameters
None.
Return value
Returns the removed first element of the array or undefined if the array is empty.
Visual RepresentationExample 1: How to Use Array shift() method
let apps = ["Insta", "Fb", "Snap"];
removed_app = apps.shift();
console.log(removed_app);
console.log(apps);
Output
Insta
[ 'Fb', 'Snap' ]
Example 2: Using a while loop
To check a specific condition, we can use a while loop.
let apps = ["Insta", "Fb", "Snap", "x"];
while( (i = apps.shift()) !== undefined ) {
console.log(apps);
}
So until the undefined value is found, it will remove each element of an array.
Output
[ 'Fb', 'Snap', 'x' ]
[ 'Snap', 'x' ]
[ 'x' ]
[]
Example 3: Using an empty array
let apps = [];
removed_app = apps.shift();
console.log(removed_app);
console.log(apps);
Output
undefined
[]
Example 4: Passing non-array objects
let arrayLikeObject = {
0: 'zero',
1: 'one',
2: 'two',
length: 3
};
let shiftedValue = Array.prototype.shift.call(arrayLikeObject);
console.log(shiftedValue);
console.log(arrayLikeObject);
Output
zero
{ '0': 'one', '1': 'two', length: 2 }
Browser compatibility
- Google Chrome 1 and above
- Edge 12 and above
- Firefox 1 and above
- Opera 4 and above
- Safari 1 and above
Post
It works really well for me
Alan
Suits!!