What is shift?
shift() method removes the first element from an array and returns the removed element.
var arr = [1,2,3,4]; //an array arr.shift(); //returns 1 //arr - [2,3,4]
The original array is modified. It is similar to pop() but acts at the start of an array.
var arr = [3,4,5,6];
Let’s use shift() to remove elements,
var returnedEl = arr.shift(); //removes 3 console.log(arr); //[4,5,6] console.log(returnedEl); //3
Now arr is [4,5,6]
var returnedEl = arr.shift(); //removes 4 console.log(arr); //[5,6] console.log(returnedEl); //4
And so on…
shift() will work with any array’s. Not only numeric or integer arrays. Let’s see an example.
var anotherArr = ["Hello", "Hi", "When", "How", "Where"]; var returnedEl = anotherArr.shift(); //removes "Hello" console.log(anotherArr); //["Hi", "When", "How", "Where"] console.log(returnedEl); //"Hello"
Can I remove multiple elements together?
No, you can’t. It removes only one element at a time. And that is the first element of the array.
What if the array is empty?
var arr = ; arr.shift(); //undefined
It’s supported in all major desktop and mobile browsers (since IE6+, Firefox 2+, Chrome 1+, etc). So, completely safe to use it, and no worries.
If you still want to check the support table, have a look at the caniuse table.
If you enjoyed this post and want similar articles to be delivered to your inbox directly, you can subscribe to my newsletters. I send out an email every two weeks with new articles, tips & tricks, news, free materials. No spamming, of course.