Javascript Array Methods: Unshift(), Shift(), Push(), And Pop()
When people first start to learn about arrays, they usually learn about the push() and pop() methods, if their particular language supports it; at least, I know I did. These two methods append elements to an array and remove an element from the an array respectively. Both of these methods work at the end of the array, where the index is largest. Javascript arrays have native support for these two methods. Javascript also has support for parallel methods that work on the beginning of the array, where the index is smallest. Unshift() and shift() are basically the same as push() and pop(), only, at the other end of the array.
Despite working with Javascript for years, I only discovered the shift() method recently. And, as for the unshift() method, I totally only learned about that last night! As such, I figured I would pass this information on in case anyone else was in the dark like myself.
Javascript Array: Push() Method
The push() method can append one or more elements to the end of an array. This alters the array on which the method was called.
// Build an array of test data.
var data = [ "X" ];
// Push data onto the array. Push() appends elements to the end
// of the given array. Note that it can take more than one
// argument, each of which is individually appended to the array.
// In the output, notice that when push() takes multiple arguments
// they are appended in a left-to-right order (mimicing their
// appearence in the arguments list).
data.push( "A" );
data.push( "B", "C" );
// Output resultant array.
console.log( data );
When we run the above code, we get the following console output:
["X", "A", "B", "C"]
The push() method can take multiple arguments, each of which will be appended to the array in the order it was passed-in (left-to-right); if you pass push() an array value, however, the array simply gets appended as a single element (a nested array). If you want to append an array to another array, take a look at the concat() method.
Javascript Array: Pop() Method
The pop() method pulls the last element off of the given array and returns it. This alters the array on which the method was called.
// Build an array of test data.
var data = [ "A", "B", "C" ];
// Pop the element off of the end of the array.
console.log( data.pop() );
console.log( data );
When we run the above code, we get the following console output:
C
["A", "B"]
If you call pop() on an empty array, it returns an undefined value.
Javascript Array: Unshift() Method
The unshift() method is like the push() method, only it works at the beginning of the array. The unshift() method can prepend one or more elements to the beginning of an array. This alters the array on which the method was called.
// Build an array of test data.
var data = [ "X" ];
// Unshift data onto the array. Unshift() prepends elements to
// the beginning of the given array. Note that it can take more
// than one argument. In the output, notice that when unshift()
// takes multiple arguments, they are prepended in a right-to-left
// order (mimicing their appearence in the arguments list).
data.unshift( "A" );
data.unshift( "B", "C" );
// Output resultant array.
console.log( data );
When we run the above code, we get the following console output:
["B", "C", "A", "X"]
Notice that when we pass the unshift() method multiple arguments, it prepends them in a right-to-left order such that the resultant array mimics the appearence of the unshift() arguments.
Javascript Array: Shift() Method
The shift() method is like the pop() method, only it works at the beginning of the array. The shift() method pulls the first element off of the given array and returns it. This alters the array on which the method was called.
// Build an array of test data.
var data = [ "A", "B", "C" ];
// Shift the element off of the beginning of the array.
console.log( data.shift() );
console.log( data );
When we run the above code, we get the following console output:
A
["B", "C"]
If you call shift() on an empty array, it returns an undefined value.
It used to be difficult for me to always keep it straight in my head which end of the array push() and pop() operated on (especially when reading unfamiliar code). But, now that I realize that unshift() and shift() are the same as push() and pop() only at the opposite end of the array, it certainly helps keep a certain mental order. I hope that this helps others at it has helped me.
Want to use code from this post? Check out the license.
Reader Comments
Thanks!
Ben,
The array method that I've been using a lot of lately that I don't see many people use is the splice() method. It allows removal (and optionally insertion ) of items at an arbitrary index in the array. It will return an array of elements removed from the array:
// Example 1
var data = [ "A", "B", "C" ];
// start at index 1, remove 1 element
data.splice(1, 1);
alert(data);
// results in: A, C
// Example 2
var data = [ "A", "B", "C" ];
// Start at index 1, remove 0 elements
// insert "X" at index 1
data.splice(1, 0, "X");
alert(data)
// results in: A, X, B, C
// Example 3
var data = [ "A", "B", "C" ];
// Start at index 1, remove 2 elements
// and insert "X" at index 1
alert(data.splice(1, 2, "X"));
// results in (return value of splice): B, C
alert(data)
// results in: A, X
Unfortunately, when you want to add multiple item, you need to add them as additional parameters at the end (as arguments 4, 5, etc), or do multiple splice() calls. If there's an easy way to get around that, it would be good to know about.
PS: The method names should probably not be capitalized in the post title and the headers within the post as JavaScript is a case-sensitive language, grammar dictates be damned. :-)
@Danilo,
Yeah, Splice() is a good method. Also, one that is kind of cool, but probably less useful, is the Slice() method. Actually, a while back, I used the Splice() method to demonstrate variable-number of arguments in ColdFusion:
www.bennadel.com/blog/1763-ColdFusion-ArraySplice-Method-As-An-Example-Of-A-Dynamic-Method-Signature.htm
As far as the capitalization, I use the case-sensitive casing in the code (of course - otherwise it wouldn't work); but when referring to code in the prose, I tend to just uppercase names in general. Something about seeing it as camel-case outside of code just feels odd. But, it would be more consistent to keep it the proper case. I will definitely consider this more deeply. Thanks.
@Danilo,
to add multiple items using splice, with no type checking etc. It even uses unshif ftw.
function multiSplice ( arrayToAddTo, index, howmany, arrayOfItemsToAdd) {
return arrayToAddTo.splice.apply(arrayToAddTo, arrayOfItemsToAdd.unshift(index, howmany) );
}
apply takes a context and an array for arguments.
@someone else,
I had a sneaky suspicion that call or apply would be part of the solution I was looking for. Thanks for posting the snippet, I'll be saving that one for sure.
Very enlightening, thanks man!
very interesting stuff, I definitely learned something.
looks like an easy way to use an array as a queue. stacks are nice, but there is something about a queue that I really like.
so we push, and shift, or unshift, and pop. First in first out queues I have found much more useful than stacks in the past so this is an awesome find for me.
Hi, how would you add an element like this :
MyArray['var1'] = 'my first element';
MyArray['var2'] = 'my second element';
at the end of an array with push, or in particular index with splice.... I get it with simple array, but can't figured it out with more complex one.
Thanks !
Thank you!!! I was trying to keep them straight and you explained it perfectly. It would be nice to know how they came up with these names in the first place.
thanks this saved my butt from wasting lot of time..
very interesting and helpful too.
Is there any function with which i can replace elements of an array..??
You capitalize "push()" and "pop()" in the titles. This will not work in javascript code. Most other online resources will keep the proper letter case, because javascript is case sensitive.
Beginners may not know this. I recommend changing "Push()" to "push()" in your titles.
Thank you, it's really helpful.
Hi Ben,
Thanks for such helpful post.
But i would also like to see the performance of the shift and unshift method if i have very large array.
let me know your thought.
bdfbdf
Thanks, nice reminder :)
Everyone looks like me!
Hey there! Very informative. I'm bookmarking this page and I'll definitely be back.
This question probably doesn't have any real world application, but I have a JavaScript exercise that asks me to .unshift a variable to the front of my array then simultaneously remove it with the .shift method.
var x = arr.unshift(x)...
How would I be able to also use a .shift in this same variable definition so that it will be processed simultaneously?
I've tried standard concatenation techniques like + arr.shift() , but I'm having no luck returning what I want.
This was a very usefull information, it really helped. I used unshift() and pop() to force a dynamically changing array adher to to a fixed size.
Thank you for sharing.