O'Reilly

Empty an Array with JavaScript

By on  

Emptying an array is a common JavaScript task but too often I see the task performed in the incorrect way.  Many times developers will create a new array:

myArray = []; // bad

That isn't the optimal way to get a fresh array;  to truncate an array, and thus empty it, you should set the length property to zero:

myArray.length = 0; // good!

Setting the length equal to zero empties the existing array, not creating another array! This helps you to avoid pointer issues with arrays as well. With the new array method above:

// ... as provided by Dag in the comments
A = [1,2,3,4,5]
B = A
A = []
console.log(B) // [1,2,3,4,5]

The length truncation would make both A and B the original array but empty!

Track.js Error Reporting

Recent Features

  • 5 Awesome New Mozilla Technologies You’ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

  • Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

Incredible Demos

  • Elegant Overflow with CSS Ellipsis

    Overflow with text is always a big issue, especially in a programmatic environment. There's always only so much space but variable content to add into that space. I was recently working on a table for displaying user information and noticed that longer strings were...

  • Create Spinning Rays with CSS3 Animations & JavaScript

    Thomas Fuchs, creator of script2 (scriptaculous' second iteration) and Zepto.js (mobile JavaScript framework), creates outstanding animated elements with JavaScript.  He's a legend in his own right, and for good reason:  his work has helped to inspire developers everywhere to drop Flash and opt...

Discussion

  1. jhuesos

    I am guilty in this one. But, anybody could add what are the cons of using the anti-pattern?

    I guess performance because you don’t have to instantiate a new object. But how the gc behaves for both approaches?

    Cheers

  2. I didn’t create my own, here is a jsperf test that seems to suggest otherwise: http://jsperf.com/array-destroy
    I’d be curious if there are situations where a.length = 0; is faster (and how many iterations are necessary to compensate for the extra bytes of download time).

    • This is a really bad test. It’s not going to give anywhere near reliable results.

  3. Asher

    Based on Kris’ actual test, it seems like a.length = 0 is worse on both readability AND performance. I would venture that most dev’s recognize a = [] at a glance, but a.length = 0 would take that much more thinking.

    • The test is entirely bogus. Don’t base your conclusions on bad benchmarks.

  4. While it does prevent allocation of a new object, in order to empty the array all the indices in it must be deleted (that’s what setting the length to 0 does). This operation may or may not be optimized, depending on how a particular js engine works.

  5. seelts

    «That isn’t the optimal way»

    Why?

  6. Dag

    I guess it is because A = [] actually does not empty the Array, it only changes the pointer.

    Example:

    A = [1,2,3,4,5]
    B = A
    A = []
    console.log(B) // [1,2,3,4,5]
    
  7. Rocka84

    I have to contradict here. As other comments stated before, the speed of the array.length approach isn’t better (if not worse) than just creating a new array and with decent garbage collectors, memory shouldn’t be a problem either.
    And even if the length property *is* writable, I personally think it *should* be treated as read-only.

    But feel free to convince me of your way, if you can ;-)

  8. My thought was avoiding reliance on garbage collection and avoiding pointer issues. Creating a new array may be more important but it does come with caveats that people need to be aware of.

  9. s/exiting/existing/

  10. Jay

    What about doing delete myArray; then?

  11. I think that a lot can be discussed on this subject without having relevant data.

    I’ve created a test script, source code: https://gist.github.com/4420845

    So we have (for reference):
    “A” – clear by using length;
    “B” – clear by using [];

    I did tests only in Google Chrome v23 on Windows 7.
    As operations per second case “B” is much faster (almost +1 million ops per sec);

    My test script loops for one second, what I noticed with case “B” is that memory is cleared faster then with method “A”. There wasn’t any memory leak (in both cases);

    @Dag & @David Walsh:
    regarding:

    A = [1,2,3,4,5]
    B = A
    A = []
    console.log(B) // [1,2,3,4,5]
    

    I tried to find in ES5 specs how this should work, but couldn’t find now, what I remember from there is that objects (arrays also apply) are set by reference
    B = A
    B points to the same data
    when you assign something to A then A will not have any more the reference to old array object, but B will continue to have data that was before on A.

    Another thing to keep in mind with ES5 that by default length property on Array has “writable” set to true, if you will set it to false this method will not work any more.

    I will stick with:myArr = []; as I have better performance and I don’t see anything wrong with it. Still if I’m missing something please post.

    @David Walsh:
    For the part “Creating a new array may be more important but it does come with caveats that people need to be aware of.”, can you explain what are the downsides?

  12. Markus

    I suppose that adding elements into an array which was cleared using .length = 0 is faster, because the memory is already allocated and it is less likeley that the js engine has to enlarge the array at runtime (which is a slow operation in other languages, dont know if it is also the case in JS).

  13. JuanO

    I’m sure that wrapping all the possible logic for clearing an array within a function would add some time to your measurements. In the end though, commented code will help with unfamiliar concepts and if .length is not writeable, well, we can handle that within the wrapper.

  14. These are my first days at giving back to the open source community and will be going by the handle TreeTopAnonymous on github as well as anywhere else that’s cool, so I hope this is helpful. I’m just starting my path into hardcore javascript development and love it so I figured I might as well optimize some techniques for my adventures.

    Test cases: http://jsperf.com/array-clearing-performance

    You can always loop through the array popping each object off which changes the actual array size as well and will allow you to remain in contain with the original array reference without having to instantiate a new array object. I do use shift() over pop() for this due to shift() being faster.

    During my tests I noticed length = 0; method starts winning at arrays >= 15000 but gets destroyed in smaller index counts so I created 3 different tests to show scaling.

    In the end my way for looping and shifting the array wins this performance battle overall unless you have the need for clearing extremely large arrays which then you could add a logic check for at over a certain amount to use the length = 0; method; then you will need to understand on faster hardware the number of 15000 will probably increase.

    • Update to previous post: Well it seems now that no matter the scaling, my shift() way beats the pants off over them both. Not sure what I was looking at before.

  15. i am agree with Dog
    because A = [] actually does not empty the Array, it only changes the pointer.

  16. I think this is a much more accurate performance test:

    http://jsperf.com/truncating-arrays-correctly

    Comments welcome if I missed anything there.

    TL;DR: the *speed* performance diffs are pretty small, and pretty irrelevant. Unquestionably, though, there will be a memory diff between = [] and .length = 0. If you care to reduce memory churn (GC), especially on mobile devices, .length = 0 is a better way to go.

  17. Ben West

    Please update this post to indicate whether all browsers (particularly legacy ones like IE7 or earlier) and execjs implementations are able to detect that the pointers to the items referenced by your array are no-longer ‘referenced’ as the array still points to them, even though they aren’t accessible via other methods: for-loops, forEach, etc.

    Also, I’d like to question when you would do this and whether is optimization isn’t universally premature, as I don’t know that I have ever assigned an empty array, except to initialize a variable for the first time.

  18. Cristian Elena

    I use:

    while(a.length){
        a.pop();
    }
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Loading Static Templates for Intern Testing

    I use Intern by SitePen for all of my JavaScript functional testing.  Intern has loads of features other functional test frameworks don't and it's completely Promise-based -- something I got very used to when I used the Dojo Toolkit every day. Async test creation can...

  • Convert Video to mp3

    Let's all be honest for a moment:  we've all ... not paid for ... music.  Whether it was via a file sharing app like Kazaa or Napster, or it was downloading and seeding on bittorrent, or maybe even downloading a music video and ripping its audio,...

  • Sort git Branches by Date

    I'll be first person to admit I don't do as much git repository maintenance as I should.  I rarely delete branches which have been merged, so a git branch execution shows me a mile-long list of branches that likely aren't relevant.  The best way to find branches I've recently...

  • Best Tools and Resources for Web Professionals in 2015

    Looking for the right resources to help you satisfy the needs of your clients? On the lookout for the best tools to help you increase your revenue? Searching for the right software to help you improve your business? Well, then you’ve come to the right place....

  • JavaScript Polling

    Polling with JavaScript is one of those ugly but important functions within advanced front-end user experience and testing practices.  Sometimes there isn't the event you can hook into to signify that a given task is complete, so you need to get your hands dirty and simply poll for...