4 ways to empty an array in JavaScript

JavaScript arrays are commonly used by developers and making them empty is also used in practice. Here I am describing 4 ways to empty an array in JavaScript:

Method I – Use splice() method

splice() method is built in function for array in JavaScript and using it will work perfectly but this function will actually return a copy of original array or an array with all the removed items. Hence it’s not enough efficient.


Method II – Set length to zero

Setting length to zero will clear the existing array. The length property of an array is a read/write property so it works well and also when using “strict mode” in Ecmascript 5.


Method III – Using pop() method

This solution might look lengthy but it is by far the faster solution (apart from set array to new empty array). Use pop() method in while loop if you are curious about performance. This is faster than using splice() method or setting length to zero.


Method IV – Set array to new empty array

if you don’t have references to the original array then setting the variable myArray to a new empty array is the perfect solution for you. Because this solution actually creates a brand new (empty) array. It’s the fastest solution and be careful and use this only if you only reference the array by its original variable.

There were generally available solutions to empty an array in JavaScript and share your opinions and the methods you use to clear an array.

You Might Interested In


  1. RaoVasim Akram Rana says:

    There are five most of the way to empty an array as below:
    var arr = [1,2,3,4,5]

    1. arr = []
    2. arr.length = 0;
    3. arr.splice(0);
    4. arr = arr.constructor();

    5. while(arr.length>0){


Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.