JavaScript > Arrays

Clear array in JavaScript

How to clear/empty an array in JavaScript


In Array section, we learnt different ways of manipulating array elements. In this post, we shall learn how to empty an array in different ways and will also understand which method is the best way to emptying an array in JavaScript.

In below code snippet, we have a function which has an array declared named a.

    function ClearArray()
    {
        var a = ["India", "Pakisthan", "Bangladesh", "China"];
        alert("Original array: " + a);

        a = ["India", "Pakisthan", "Bangladesh", "China"];
        a.length = 0;
        alert("1st output: " + a);

        // 2nd way
        a = ["India", "Pakisthan", "Bangladesh", "China"];
        a = [];
        alert("2nd output: " + a);
    
        // 3rd way
        a = ["India", "Pakisthan", "Bangladesh", "China"];
        a.splice(0, a.length);
        alert("3rd output: " + a);    
    
        // 4th way
        a = ["India", "Pakisthan", "Bangladesh", "China"];
        while(a.length)
        {
            a.pop();
        }
        alert("4th output: " + a);
    }

We are doing following in the above code snippet

  • First we are declaring an array and setting 4 strings into it.
  • Showing the element of the array in alert
    1. The 1st way of clearing the array is to set it's length to 0
    2. The 2nd way of clearing the array is to set it's new value to empty array
    3. The 3rd way of clearing the array is to use the slice method and remove all the element starting from 0 to the length of the array.
    4. The 4th way of clearning the array is to use while loop to the length of the array and call the pop method to remove each elements.

Which is the best way of clearing array?

After testing we have come to the conclusion that 2nd and 3rd way is better than any others.

 Views: 5676 | Post Order: 159



Write for us






Hosting Recommendations