A Web Design Community curated by Chris Coyier

A little dab'll do ya

Code Snippets

Home » Code Snippets » JavaScript » Empty an Array Submit one!

Empty an Array

This is one of the fastest and easiest ways of emptying an array. Of course there are may other ways, but those usually include creation of a new array. This way you reuse the same array.

var myArray = ["one", "two", "three"];

// console.log( myArray ) => ["one", "two", "three"]

myArray.length = 0;

// console.log( myArray ) => []

Subscribe to The Thread

  1. ng87 says:

    isnt:

    myArray = [];

    just as good?

  2. CaTaHaC says:

    I bet this:
    myArray.length = 0;
    does not work in all browsers where the snippet provided above – does.

  3. Plr store says:

    Excellent code, myArray.empty() works as well.

    • Tem Corner says:

      it’s not a standard prototype on the Array constructor.
      Atleast not in the latest WebKit browsers.

  4. Genzeb says:

    Ha, just do:
    arrayobj.splice(0,arrayobj.length).

    You can even add that to a prototype as

    Array.prototype.empty() {this.splice(0,this.length);}

    and you are done.

  5. Lu1s says:

    I think:

    myArray = [];
    /* or */
    myArray = new Array();

    Would be the best, since it’s cross-browser stuff.

  6. Matt W says:

    The problem with myArray = [] and myArray = new Array() is that technically you are not emptying the array, but instead you are creating a new array. Creating new arrays is a bit of work for browsers, so simply setting the array’s length to 0 is probably best.

  7. Nisse says:

    none of the examples works

    • zenoob says:

      Out of the above I’ve only tested emptying an array through splicing and it did work perfectly.

It's Your Turn

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
--- The Management ---