How to empty an array in JavaScript?

For instance,

 var arrayList =  ['a','b','c','d','e','f'];

How can we empty the array above?

There are a couple ways we can use to empty an array, so let’s discuss them all.

Method 1

arrayList = []

Above code will set the variable arrayList to a new empty array. This is recommended if you don’t have references to the original array arrayListanywhere else, because it will actually create a new, empty array. You should be careful with this method of emptying the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged.

For Instance,

var arrayList = ['a','b','c','d','e','f']; // Created array 
var anotherArrayList = arrayList;  // Referenced arrayList by another variable 
arrayList = []; // Empty the array 
console.log(anotherArrayList); // Output ['a','b','c','d','e','f']

Method 2

arrayList.length = 0;

The code above will clear the existing array by setting its length to 0. This way of emptying the array also updates all the reference variables that point to the original array. Therefore, this method is useful when you want to update all reference variables pointing to arrayList.

For Instance,

var arrayList = ['a','b','c','d','e','f']; // Created array 
var anotherArrayList = arrayList;  // Referenced arrayList by another variable 
arrayList.length = 0; // Empty the array by setting length to 0
console.log(anotherArrayList); // Output []

Method 3

arrayList.splice(0, arrayList.length);

The implementation above will also work perfectly. This way of emptying the array will also update all the references to the original array.

var arrayList = ['a','b','c','d','e','f']; // Created array 
var anotherArrayList = arrayList;  // Referenced arrayList by another variable 
arrayList.splice(0, arrayList.length); // Empty the array by setting length to 0
console.log(anotherArrayList); // Output []

Method 4

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

The implementation above can also empty arrays, but it is usually not recommended to use this method often.

Asked on January 18, 2019 in Javascript.
Add Comment


  • 10 Answer(s)
    let xs = [1,2,3,4];
    for (let i in xs)
        delete xs[i];

    This yields an array in quite a different state from the other solutions. In a sense, the array has been ’emptied’:

    xs
    => Array [ <4 empty slots> ]
    
    [...xs]
    => Array [ undefined, undefined, undefined, undefined ]
    
    xs.length
    => 4
    
    xs[0]
    => ReferenceError: reference to undefined property xs[0]

    You can produce an equivalent array with [,,,,] or Array(4)

    Answered on January 19, 2019.
    Add Comment

    This code will set the variable A to a new empty array. This is perfect if you don’t have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.

    This is also the fastest solution.

    This code sample shows the issue you can encounter when using this method:

    var arr1 = ['a','b','c','d','e','f'];
    var arr2 = arr1;  // Reference arr1 by another variable 
    arr1 = [];
    console.log(arr2); // Output ['a','b','c','d','e','f']
    Answered on January 20, 2019.
    Add Comment

    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!

    Answered on January 27, 2019.
    Add Comment

    while keeping the same array (“mutable”):

    Array.prototype.clear = function() {
    while (this.length) {
    this.pop();
    }
    };
    FYI Map defines clear() so it would seem logical to have clear() for Array too.

    Or as an Underscore.js mixin:

    _.mixin({
    clearArray: function(array) {
    while (array.length) {
    array.pop();
    }
    }
    });
    Or a simple function:

    function clearArray(array) {
    while (array.length) {
    array.pop();
    }
    }
    TypeScript version:

    function clearArray(array: T[]) {
    while (array.length) {
    array.pop();
    }
    }
    FYI it cannot be simplified to while (array.pop()): the tests will fail.

    And the tests that goes with it:

    describe(‘Array’, () => {
    it(‘should clear the array’, () => {
    let array = [1, 2, 3, 4, 5];
    array.clear();
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);

    // Even with undefined or null inside
    array = [1, undefined, 3, null, 5];
    array.clear();
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);
    });
    });

    Answered on January 27, 2019.
    Add Comment

    // define Array
    var list = [1, 2, 3, 4];
    function empty() {
    //empty your array
    list = [];
    }
    empty();
    But there is another way to empty an array that is more performant.

    You should use code like this:

    var list = [1, 2, 3, 4];
    function empty() {
    //empty your array
    list.length = 0;
    }
    empty();

    Answered on February 2, 2019.
    Add Comment
    • list = [] assigns a reference to a new array to a variable, while any other references are unaffected. which means that references to the contents of the previous array are still kept in memory, leading to memory leaks.
    • list.length = 0 deletes everything in the array, which does hit other references.

    In other words, if you have two references to the same array (a = [1,2,3]; a2 = a;), and you delete the array’s contents using list.length = 0, both references (a and a2) will now point to the same empty array. (So don’t use this technique if you don’t want a2 to hold an empty array!)

    Think about what this will output:

    var foo = [1,2,3];
    var bar = [1,2,3];
    var foo2 = foo;
    var bar2 = bar;
    foo = [];
    bar.length = 0;
    console.log(foo, bar, foo2, bar2);
    
    // [] [] [1, 2, 3] []
    Answered on February 3, 2019.
    Add Comment

    Method 1

    (this was my original answer to the question)

    A = [];
    This code will set the variable A to a new empty array. This is perfect if you don’t have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.

    This is also the fastest solution.

    This code sample shows the issue you can encounter when using this method:

    var arr1 = [‘a’,’b’,’c’,’d’,’e’,’f’];
    var arr2 = arr1; // Reference arr1 by another variable
    arr1 = [];
    console.log(arr2); // Output [‘a’,’b’,’c’,’d’,’e’,’f’]
    Method 2 (as suggested by Matthew Crumley)

    A.length = 0
    This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using “strict mode” in ECMAScript 5 because the length property of an array is a read/write property.

    Method 3 (as suggested by Anthony)

    A.splice(0,A.length)
    Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.

    Method 4 (as suggested by tanguy_k)

    while(A.length > 0) {
    A.pop();
    }

    Answered on February 4, 2019.
    Add Comment

    This code sample shows the issue you can encounter when using this method:

    var arr1 = ['a','b','c','d','e','f'];
    var arr2 = arr1;  // Reference arr1 by another variable 
    arr1 = [];
    console.log(arr2); // Output ['a','b','c','d','e','f']
    Answered on February 5, 2019.
    Add Comment

    There are no in-built functions and properties available to calculate the length of associative array object here. However, there are other ways by which we can calculate the length of an associative array object. In addition to this, we can also extend an Object by adding a method or property to the prototype in order to calculate length. However, extending an object might break enumeration in various libraries or might create cross-browser issues, so it’s not recommended unless it’s necessary. Again, there are various ways by which we can calculate length.

    Object has the keys method which can be used to calculate the length of an object:

    
    We can also calculate the length of an object by iterating through an object and by counting the object's own property.  
    
    ```javascript
    function getSize(object){
      var count = 0;
      for(key in object){
        // hasOwnProperty method check own property of object
        if(object.hasOwnProperty(key)) count++;
      }
      return count;
    }
    

    We can also add a length method directly on Object:

    Object.length = function(){
      	var count = 0;
      for(key in object){
        // hasOwnProperty method check own property of object
        if(object.hasOwnProperty(key)) count++;
      }
      return count;
    }
    //Get the size of any object using
    console.log(Object.length(counterArray))
    Answered on February 5, 2019.
    Add Comment

    You define an array and want to empty its contents. Usually, you would do it like this:

    // define Array
    var list = [1, 2, 3, 4];
    function empty() {
    //empty your array
    list = [];
    }
    empty();
    But there is another way to empty an array that is more performant.

    You should use code like this:

    var list = [1, 2, 3, 4];
    function empty() {
    //empty your array
    list.length = 0;
    }
    empty();

    Answered on February 21, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.