Join the DZone community and get the full member experience.Join For Free
Buckled up and all set to kick-start your Agile transformation journey? 10 Road Signs to watch out for in your Agile journey. Brought to you in partnership with Jile.
How to Empty an Array? The Allocation Way
The first answer that I occasionally see is to allocate a new array:
var a = [1, 2, 3]; // later in code a = ;
While this method will empty the array, it might lead to reference problems. A reference problem will happen if you have another reference to the original array. For example:
var a = [1, 2, 3], b = a; // later in code a = ; console.log(b); // will print [1, 2, 3]
In the previous code we thought that we emptied both a and b arrays but it might lead to an error later because the b array didn’t get empty.
How to Empty an Array? My Preferred Solution
var a = [1, 2, 3]; // later in code a.length = 0
By setting the array length to 0 you empty an array and you won’t allocate a new array in the process. This method will also help you avoiding reference problems like the one I showed earlier:
var a = [1, 2, 3], b = a; // later in code a.length = 0; console.log(b); // will print 
Here the console will print an empty array both for a and b arrays.
If you want to see the performance implications of using one of this methods you can go to the this linkwhich include a benchmark that check both of these methods in various of browsers.
Published at DZone with permission of Gil Fink , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.