The JavaScript shift method removes the first element from the array and returns that element.
While it may be tempting to use the Array.prototype.splice() method to remove an element from the beginning of a JavaScript array, believe me, Array.prototype.shift() is the best way to do it. And just as a side note, I’ve always felt that the method name “shift” is a little odd, but that’s what the ECMAScript specification calls for, so we’ll just move along with the good stuff.
So, with the Array.prototype.shift() method, it’s the syntax that’s really important, and the beauty of it is, it’s quite simple. You just chain .shift() onto your array variable name, without passing any arguments. For example: myArray.shift() would remove the first element from the beginning of the “myArray” array. Just keep in mind that the .shift() method returns the element that was removed from the beginning of the array. So, for example, if an array has five elements and the first one is the string “ABC”, calling the .shift() method will return “ABC”, because it has removed that element from the beginning of the array.
Try it yourself !
In the above example, we have the foo array, which has six elements. Each time we call the shift method, the first element of that array is removed. Notice that we show the return value of the shift method in the console. So, we can see that shift returns the element that was returned.
Click the Result tab. Notice how we call the shift method a total of three times. Each time, we show the return of that call to shift: “a”, “b”, and “c”. We also show the length of the foo array each time as well. That length decreases each time we call shift, so the values are 5, 4, and 3. And finally, each time we call shift, we use the console.dir method to inspect foo, so that we can see the changes that are happening to the array with each call to shift.
So, to recap, the ECMAScript specification provides a number of methods on the Array.prototype object that are designed for handling mutations to the beginning and end of an array. But the Array.prototype.shift() method specifically functions to efficiently remove the first element from the beginning of an array. This method takes no arguments and returns the element that was removed from the beginning of the array. Simplicity and efficiency at its best!
When you need to work with the first or last elements in a JavaScript array, the push(), pop(), shift() and unshift() methods are usually the best way to go.
Programmers who are new to JavaScript or come to it via languages such as PHP may find arrays a bit limiting. The main issue is usually the fact that in JavaScript, there are no associative arrays. While that may seem frustrating, associative array-like functionality can be achieved by leveraging the power and simplicity of objects. Although JavaScript arrays are restricted to numeric-based property names, they are otherwise quite flexible.
Since JavaScript array elements must have numeric property names, they are essentially anonymous. From a programmatic standpoint, the only array elements that you absolutely know anything about are the first and last elements in the array. And when an array has only one element, the first and last elements are one in the same.
The JavaScript Array object provides four very useful methods: push(), pop(), shift() and unshift(). To be precise, these methods belong to the Array object’s prototype property. We know this because every array you create shares a copy of these four methods (that is because every array you create is an instance of the Array constructor).
These four methods allow us to programmatically work with the only two elements of an array that we can be sure about: the beginning and the end. Every element between the first and last is a mystery to us because, from a purely programmatic standpoint, we have no idea how many there are or what they are. We only know that as long as an array has at least one element, it has a first and last element.
The JavaScript Array.push() Method
The JavaScript Array.push() method adds a new element to the end of the array. When doing so, the array’s length property increases by one. After adding the new element to the end of the array, this method returns the new length of the array.
Example # 1
1
2
3
4
5
6
7
vardays=['mon','tues','wed'];
console.dir(days);
console.log(days.push('thurs'));//4
console.dir(days);
In Example # 1, our array starts out with three elements. The first console.dir() call allows you to inspect it in your console and see that it contains only: ‘mon‘,’tues‘,’wed‘. We then use the Array object’s push() method to add a new element to the end of the array (“thurs”). Notice that when we do this, we wrap the call in a console.log() call, allowing us to see that the push() method has returned the new length of the array: 4. Then, another console.dir() call allows us to inspect the array, demonstrating that “thurs” was, in fact, added to the end of the array.
The JavaScript Array.pop() method removes the last element from the end of the array. When doing so, the array’s length property decreases by one. After removing the last element from the end of the array, this method returns the array element that was removed.
Example # 2
1
2
3
4
5
6
7
vardays=['mon','tues','wed'];
console.dir(days);
console.log(days.pop());//wed
console.dir(days);
In Example # 2, our array starts out with three elements. We then use the Array object’s pop() method to remove the last element from the end of the array (“wed”). Notice that when we do this, we wrap the call in a console.log() call, allowing us to see that the pop() method has returned the element that was removed from the end, which in this case is “wed”. Then, another console.dir() call allows us to inspect the array, demonstrating that “wed” was in-fact removed from the end of the array.
The JavaScript Array.shift() method removes the first element from the beginning of the array. When doing so, the array’s length property decreases by one. After removing the first element from the beginning of the array, this method returns the array element that was removed.
Example # 3
1
2
3
4
5
6
7
vardays=['mon','tues','wed'];
console.dir(days);
console.log(days.shift());//mon
console.dir(days);
In Example # 3, our array starts out with three elements. We then use the Array object’s shift() method to remove the first element from the beginning of the array (“mon”). Notice that when we do this, we wrap the call in a console.log() call, allowing us to see that the shift() method has returned the element that was removed from the beginning, which in this case is “mon”. Then, another console.dir() call allows us to inspect the array, demonstrating that “mon” was, in fact, removed from the beginning of the array.
The JavaScript Array.unshift() Method
The JavaScript Array.unshift() method adds a new element to the beginning of the array. When doing so, the array’s length property increases by one. After adding the new element to the beginning of the array, this method returns the new length of the array.
Example # 4
1
2
3
4
5
6
7
vardays=['mon','tues','wed'];
console.dir(days);
console.log(days.unshift('sun'));//4
console.dir(days);
In Example # 4, our array starts out with three elements. The first console.dir() call allows you to inspect it in your console and see that it contains only: ‘mon’,’tues’,’wed’. We then use the Array object’s unshift() method to add a new element to the beginning of the array (“sun”). Notice that when we do this, we wrap the call in a console.log() call, allowing us to see that the unshift() method has returned the new length of the array: 4. Then, another console.dir() call allows us to inspect the array, demonstrating that “sun” was, in fact, added to the beginning of the array.
Summary
In this article, we learned about the JavaScript Array’s push(), pop(), shift() and unshift() methods. We also learned that all JavaScript arrays can leverage these methods to work programmatically with the beginning and end of the array, regardless of how many elements are in between. Additionally, we learned that in two cases, the new length of the array is returned, and in the other two cases, the element that was removed is returned.
Helpful Links for the JavaScript Array’s push(), pop(), shift() and unshift() methods
Sometimes you have multiple JavaScript functions that you need to execute in a specific order, but do not know the details ahead of time
Both jQuery and Dojo offer their own flavor of “Deferred” functionality. This is a pretty deep topic that, while a bit challenging, offers tremendous power with respect to queuing up an invocation of multiple functions in an orderly manner. One concept that plays into this way of thinking is using the JavaScript array object’sshift() method. It easily fires off some functions in order, even when you don’t know ahead of time how many there will be.
Example # 1
1
vara=function(){console.log("this is function: a")}
var b = function(){ console.log(“this is function: b”) } var c = function(){ console.log(“this is function: c”) } var foo = [a,b,c]; while (foo.length){ foo.shift().call(); }
In example # 1, we define three functions. Then, we build an array with each element being a reference to one of our functions. Now, using a while loop, we call each function. There is a cool interplay going on here. For the while loop, as long as foo has length (that is as long as the length of foo does not return a “falsy” value, such as zero), the loop will run. Inside the loop, the JavaScript shift() method not only removes the first element from the array, it also returns that element. So, we chain onto that return value, which is the function itself, and use the JavaScript .call() method, to actually invoke the function. With each iteration of the while loop, the array looses an element. It therefore becomes smaller and smaller until finally, “foo.length” returns zero, which is “falsy,” and the loop no longer runs.
The end result here is that you can have a list of functions that you can execute, one at a time, in a specified order, and each function runs only once. A much more practical use for this technique is when you are adding methods to the array (i.e. our “queue”), at run time. You don’t know how many you might add, or what they might do, but you know that you can line ’em up, and fire ’em off!
Summary
Because so much of what the Front End Web Developer deals with happens in the life of a page, there are many circumstances in which you are not sure how many of something will come along. But if you are able to get your hands around such dynamic events, you can handle some pretty cools scenarios. Invoking an unknown number of functions at runtime is such a case. This technique provides a fairly simple way to implement this approach.
Helpful links for the JavaScript Array Object’s shift() Method