Empty an Array in JavaScript

How can I clear an array in JavaScript? Is there a method like .remove() to empty an array?

For example, if I have an array A = [1,2,3,4];, how can I empty it?

I’ve been working with JavaScript for over a decade, and there are several effective ways to clear an existing array A in JavaScript:

  1. Assigning an Empty Array: Simply assign an empty array to the variable A. This creates a new empty array, so be cautious if you have other references to the original array A.

    A = [];
    
  2. Setting Length to 0: Set the length property of the array to 0. This effectively truncates the array to an empty length.

    A.length = 0;
    
  3. Using splice(): Use the splice() method to remove all elements from the array. This method returns a copy of the removed elements, but in this case, all elements are removed.

    A.splice(0, A.length);
    
  4. Using a While Loop: Use a while loop to continuously remove elements from the end of the array until its length is 0. This method is less succinct and slower compared to the others.

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

Performance-wise, methods 2 and 3 are the fastest for clearing an array. However, the choice of method depends on your specific use case and coding style.

With my experience, I’d like to add that a more universally compatible and efficient approach is to use the splice method to empty the array A:


A.splice(0, A.length);

This method works reliably across different environments and maintains the reference to the original array, which can be important in certain contexts.

Drawing from my years of JavaScript development, you can enhance your JavaScript files by adding a method to clear arrays conveniently:

Array.prototype.clear = function() {
    this.splice(0, this.length);
};

Then, you can use it like this:

var list = [1, 2, 3];
list.clear();

To avoid overwriting existing methods, you can add a check before defining it:

if (!Array.prototype.clear) {
    Array.prototype.clear = function() {
        this.splice(0, this.length);
    };
}

While this approach can be useful, it’s generally advised to be cautious when modifying native objects like Array. It ensures you don’t inadvertently introduce conflicts with existing or future properties and methods.