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 »
10,640 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 !


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
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 12, 2012 at 3:37 AM
Learning ColdFusion 8: CFImage Part III - Watermarks And Transparency
Hi Ben, Just to ask currently it is placed bottom right corner, if i need to replace the same rendered image on the bottom left side or in the bottom center, how that can be calculated. bottom ce ... read »
Feb 11, 2012 at 9:29 PM
Use jQuery's SlideDown() With Fixed-Width Elements To Prevent Jumping
I can't say how glad I am that I found your post. Thank you very much. ... read »
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »