W3docs

How to Empty an Array in JavaScript

This tutorial provides useful information about clearing an existing array in JavaScript. Get familiar to multiple methods and find the best one for you.

Sometimes, you want to empty an array instead of creating a new one. However, there are multiple ways of clearing an array which we are going to discuss in this tutorial to make it much easier for you.

Let's assume we have an array, and we want to clear it.

The first method can be the following:

javascript array

let arr = [];

Running the code above will set the <kbd class="highlighted">arr</kbd> to a new clean array. Use this method if you only reference the array by its original variable arr. Note that this reassignment creates a new array, so the original array will remain unchanged if it is referenced by another variable or property.

Here is an issue example you may encounter:

Javascript reference array

javascript— editable

Another method you can encounter is setting the length of the array to 0.

javascript array length

arr.length = 0;

Javascript array length

javascript— editable
Info

This method also works in strict mode, since the length property is writable.

The third method is using .splice(), which also works. Note that it returns an array containing the removed items, not a copy of the original.

javascript array splice

arr.splice(0, arr.length)

All the methods mentioned above are similar and can be used to clear the existing array, but the second and third methods are generally faster. Use the first method when you don't need to preserve references to the original array, and the second or third when you need to mutate the existing array in place.

Arrays

Arrays are used to store several values in one variable. Neither the length of an array nor the types of its elements are fixed. Whenever you change the array, the length property automatically updates. It reflects the highest numeric index plus one, rather than the exact count of elements. The length property is writable. When you decrease it, the array will be truncated.