.NET Zone is brought to you in partnership with:

Gil Fink, Microsoft MVP, is an expert in Web development and Microsoft data platform. He works as a senior architect at Sela Group. He is currently consulting for various enterprises and companies, where he architects and develops Web and RIA-based solutions. He conducts lectures and workshops for developers and enterprises who want to specialize in infrastructure and Web development. He is also a co-author of several Microsoft Official Courses and training kits. You can read his publications at his blog: http://blogs.microsoft.co.il/blogs/gilf. Gil is a DZone MVB and is not an employee of DZone and has posted 150 posts at DZone. You can read more from them at their website. View Full User Profile

Quick Tip – Empty a JavaScript Array

09.23.2013
| 4487 views |
  • submit to reddit

The question of how to empty an array in JavaScript is being raised from time to time. If you will look at the JavaScript array API you will find that the array objects in JavaScript don’t include an empty/remove function.

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 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

The way I empty a JavaScript array is using the following code:

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.

Summary

JavaScript arrays don’t include an API way to empty their content. In this post I showed two ways to empty a JavaScript array.

Published at DZone with permission of Gil Fink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)