Monday, 19 January 2015

Filled Under:

How to Empty an array in JavaScript?

For instance,
A is an array in a JavaScript program.
A = [1,2,3,4];
How to empty that?
By empty we mean Clear/Clean the Array and not delete or remove Array itself in this case A.

Method 1:


//Set A to a new empty array
A = [];

Its that simple. 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.

Method 2:


//Set arrat length to zero 0
A.length = 0
This will clear the existing array by setting its length to 0. It also works when using "strict mode" in Ecmascript 5(JS5) because the length property of an array is a read/write property.

Method 3:


//Using Splice method
A.splice(0,A.length)
Using .splice() will work perfectly, but it's not very efficient because the .splice() function will return an array with all the removed items, so it will actually return a copy of the original array.

Method 4:

This solution is not very succinct but it is by far the fastest solution (apart from setting the array to a new array). If you care about performance, consider using this method to clear an array. Benchmarks show that this is at least 10 times faster than setting the length to 0 or using splice().

//using while loop with pop method
while(A.length) {
    A.pop();
}

0 comments:

Post a Comment