Over a million developers have joined DZone.
Silver Partner

Quick Tip – Empty a JavaScript Array

· Agile Zone

The Agile Zone is brought to you in partnership with Zephyr. Learn more about the implementation of a Test Management system to automate business processes is a strategic investment for any development and QA project team.

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.

The Agile Zone is brought to you in partnership withZephyr. Learn more about the implementation of a Test Management system to automate business processes is a strategic investment for any development and QA project team.

Topics:

Published at DZone with permission of Gil Fink , DZone MVB .

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}