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

Upcoming Events

Recent Features

  • 9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

  • From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!

    My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects...

Incredible Demos

  • Multiple Backgrounds with CSS

    Anyone that's been in the web development industry for 5+ years knows that there are certain features that we should have had several years ago. One of those features is the HTML5 placeholder; we used JavaScript shims for a decade before placeholder came...

  • The Simple Intro to SVG Animation

    This article serves as a first step toward mastering SVG element animation. Included within are links to key resources for diving deeper, so bookmark this page and refer back to it throughout your journey toward SVG mastery. An SVG element is a special type of DOM element...

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

  • Free Download: Font Bundle Featuring 17 Incredible Typefaces

    The only thing we love more than a good font, is a good free font. So we’ve combed the Web for some of our favorite free fonts, and gathered them here in a single download. You’ll find a variety of useful typefaces, from highly geometric designs...

  • OâReilly Velocity Conference â Amsterdam

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • CanIUse Command Line

    Every front-end developer should be well acquainted with CanIUse, the website that lets you view browser support for browser features.  When people criticize my blog posts for not detailing browser support for features within the post, I tell them to check CanIUse:  always up to date, unlike...

  • Generating Alternative Stylesheets for Browsers Without @media

    If your CSS code is built with a mobile-first approach, it probably contains all the rules that make up the "desktop" view inside @media statements. That's great, but browsers that don't support media queries (IE 8 and below) will simply ignore them, ending up getting the...

  • Serve a Directory with PHP

    Many developers have a giggle at PHP, even looking down at the language, but let's be honest:  most of our blogs are powered by it (WordPress) and it's a great language to dabble around with.  I cut my teeth on PHP, though I prefer to avoid PHP these days. But...