Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Quick Tip – Empty a JavaScript Array

DZone's Guide to

Quick Tip – Empty a JavaScript Array

· Agile Zone
Free Resource

See how three solutions work together to help your teams have the tools they need to deliver quality software quickly. Brought to you in partnership with CA Technologies

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.

Discover how TDM Is Essential To Achieving Quality At Speed For Agile, DevOps, And Continuous Delivery. Brought to you in partnership with CA Technologies

Topics:

Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}