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

  • Animated 3D Flipping Menu with CSS

    CSS animations aren't just for basic fades or sliding elements anymore -- CSS animations are capable of much more.  I've showed you how you can create an exploding logo (applied with JavaScript, but all animation is CSS), an animated Photo Stack, a sweet...

  • LightFace:  Facebook Lightbox for MooTools

    One of the web components I've always loved has been Facebook's modal dialog.  This "lightbox" isn't like others:  no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much."  With Facebook's dialog in mind, I've created LightFace:  a Facebook lightbox...

Incredible Demos

  • Fix Anchor URLs Using MooTools 1.2

    The administrative control panel I build for my customers features FCKEditor, a powerful WYSIWYG editor that allows the customer to add links, bold text, create ordered lists, and so on. I provide training and documentation to the customers but many times they simply forget to...

  • HTML5 Input Types Alternative

    As you may know, HTML5 has introduced several new input types: number, date, color, range, etc. The question is: should you start using these controls or not? As much as I want to say "Yes", I think they are not yet ready for any real life...


  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?


  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»


  6. Dag

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


    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:

    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:


    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:


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

  • OSCON Portland:  Conference  Discount!

    O'Reilly puts on the best web industry conferences in the world.  These conferences include Fluent Conference, Velocity Conference, and the upcoming OSCON in Portland, Oregon from July 20-24.  Open Source Convention (OSCON) is a conference that focuses specifically on open source developers and the tools and possibilities...

  • Follow Redirects with cURL

    I love playing around with cURL. There's something about loading websites via command line that makes me feel like some type of smug hacker, just like tweeting from command line does. I recently cURL'd the Google homepage and saw the following: I found it weird that Google...

  • Developers Have WordPress, Amateurs Have Squarespace, Professional Designers Have the NEW Webydo!

    Web design platforms have traditionally come in one of two varieties. There are the solutions like WordPress and Drupal that are incredibly powerful, but an understanding of web development and coding is required to be able to use those platforms effectively. On the other side of the...

  • Chris Coyierâs Favorite CodePen Demos II

    Hey everyone! Before we get started, I just want to say it’s damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so...

  • GSAP + SVG For Power Users: Motion Along A Path

    Now that the GreenSock API is picking up steam, there are many tutorials and Getting Started guides out there to provide good introductions to the library, not to mention GreenSock’s own Forum and Documentation. This article isn’t intended for beginners, but rather a...