Javascript Array Methods: Unshift(), Shift(), Push(), And Pop()

Posted December 29, 2009 at 8:49 AM by Ben Nadel

Tags: Javascript / DHTML

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.




Reader Comments

Dec 29, 2009 at 10:35 AM // reply »
26 Comments

Thanks!


Dec 29, 2009 at 4:26 PM // reply »
21 Comments

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. :-)


Dec 30, 2009 at 8:10 AM // reply »
11,232 Comments

@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:

http://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.


Jan 19, 2010 at 3:23 AM // reply »
2 Comments

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


Jan 20, 2010 at 3:20 PM // reply »
21 Comments

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


Jun 7, 2011 at 9:37 AM // reply »
1 Comments

Very enlightening, thanks man!


Jun 9, 2011 at 3:10 AM // reply »
2 Comments

very interesting stuff, I definitely learned something.


Jan 13, 2012 at 11:27 AM // reply »
1 Comments

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.


Feb 6, 2012 at 5:49 AM // reply »
1 Comments

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 !


Jan 24, 2013 at 2:59 PM // reply »
1 Comments

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.


Feb 4, 2013 at 7:01 AM // reply »
1 Comments

thanks this saved my butt from wasting lot of time..


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 17, 2013 at 7:42 PM
HashKeyCopier - An AngularJS Utility Class For Merging Cached And Live Data
Ben - thanks so much for posting these Angular articles and findings, they've been a huge help towards learning one of the more 'complex' JavaScript frameworks out there (IMO). I have been using Angu ... read »
May 16, 2013 at 5:01 PM
UPDATE: Parsing CSV Data Files In ColdFusion With csvToArray()
Your code was the closest thing I've found to obtaining some direction for converting ISO fields to values that CF can translate properly. Thank you for posting! ... read »
May 15, 2013 at 10:37 PM
Very Simple Pusher And ColdFusion Powered Chat
hi id making plz easy ... read »
May 15, 2013 at 6:07 PM
Making SOAP Web Service Requests With ColdFusion And CFHTTP
Ben, you once again saved my bacon at work. Thank you, thank you, thank you! ... read »
May 15, 2013 at 4:15 PM
What If All User Interface (UI) Data Came In Reports?
@Josh, Thanks! @Ben, I definitely recommend the David West book "Object Thinking" I've been quoting from. It goes deeply into the philosophy and history of OO programming. His breadth ... read »
May 15, 2013 at 11:36 AM
Ask Ben: Print Part Of A Web Page With jQuery
I found this helpfull when you need to keep (refresh) the original parent page after closing the iframe child print dialog (Hoping you're not using a form at this time so it won't submit again): On ... read »
May 14, 2013 at 7:13 PM
What If All User Interface (UI) Data Came In Reports?
@Jonah, If there's any books you'd recommend on the subject of domain modelling, I'd love to hear it. I just downloaded the free PDF of "Domain Driven Design Quickly". Figured I'd give it ... read »
May 14, 2013 at 6:57 PM
The UX Of Prototyping: Low-Fidelity Is The New High-Fidelity
@Phillip, I'm not sure I follow what you mean? Are you saying that you looked at the list of widgets provided by the jQuery UI and let that be your style guide? ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools