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!

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

  • Responsive Images: The Ultimate Guide

    Chances are that any Web designers using our Ghostlab browser testing app, which allows seamless testing across all devices simultaneously, will have worked with responsive design in some shape or form. And as today’s websites and devices become ever more varied, a plethora of responsive images...

  • How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

Incredible Demos

  • Custom Scrollbars in WebKit

    Before each of the browser vendors we like was providing unique CSS controls, Internet Explorer was setting the tone.  One such example is IE's early implementation of CSS filters. Internet Explorer was also the first browser that allowed developers to, for better or worse, customize...

  • Do / Undo Functionality with MooTools

    We all know that do/undo functionality is a God send for word processing apps. I've used those terms so often that I think of JavaScript actions in terms of "do" an "undo." I've put together a proof of concept Do/Undo class with MooTools. The MooTools...

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

  • Access Mac Camera by Command Line

    With all of my recent command line tutorials, I've really gotten excited about the shell's simplicity and realized the true power of using the underlying technology of pretty UIs.  Since I work from home, I spend a lot of time on video calls, so when...

  • Open Files from Command Line on OS X

    I'm as much of a fan of application UIs as anyone else but I'm finding myself working more and more from the command line lately.  Much of that is becoming obsessed with media manipulation but I'm forcing myself to use less UIs so that I...

  • Get Stock Quotes From Command Line

    When I conned my way into my first professional programming gig, I didn't really think much about money -- just that I was getting my foot in the door.  But as my career has gone on, I've been more aware of money, investing, and retirement.  I've recently...

  • Geolocation API

    One interesting aspect of web development is geolocation; where is your user viewing your website from? You can base your language locale on that data or show certain products in your store based on the user's location. Let's examine how you can...

  • Create an Image Preview from a Video

    Visuals are everything when it comes to media.  When I'm trying to decide whether to watch a video on Netflix, it would be awesome to see a trailer of some kind, but alas that isn't available.  When I'm looking to download a video on my computer,...