Subscribe to get my new tutorials in your inbox.

What is shift() in JavaScript?

What is shift() in JavaScript?

We have heard about Array push and pop methods and how they can be used to add or remove elements from the end of an array. JavaScript provides two more useful methods – unshift and shift to add or remove elements at the start of an array. Today we are going to look at what is shift in JavaScript and how we can use it.

What is shift?

The 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.

Examples

I have defined a JavaScript array below,

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?

Returns undefined.

var arr = [];
arr.shift(); //undefined

Browser Support

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.


Write a Comment

Your email address will not be published. Required fields are marked *