How to empty an array in Javascript?


Is there a way to empty an array or just delete it?

For example:

A = [1,2,3,4];

How would it be emptied?

PS: This question already exists in the English version, but I found it interesting to take it up again and adapt it for Spanish-speaking users.


If a new instance is assigned to the array, it can be cleaned:

 var numeros = [1,2,3,4,5]; console.log(numeros); numeros = []; // nueva instancia console.log(numeros);

Also using the splice() method that removes from the original array and returns the elements in the specified range. So you would have another instance of an array:

 var numeros = [1,2,3,4,5]; console.log(numeros); var elementosRemovidos = numeros.splice(0, numeros.length); console.log(elementosRemovidos); console.log(numeros);

Also using JavaScript's pop() method that removes the last element from the array . So to clean it completely you would have to execute the pop() method for each element of the array :

 var numeros = [1,2,3,4,5]; console.log(numeros); numeros.pop(); // elimina el elemento 5 console.log(numeros); while(numeros.length > 0) numeros.pop(); console.log(numeros);

And finally assigning 0 to the length property. According to the documentation :

You can set the length property to truncate an array at any time. When extending an array by changing its length property, the number of actual elements does not increase; for example, if you set length to 3 when it is currently 2, the array still contains only 2 elements. Therefore, the length property does not necessarily indicate the number of values ​​defined in the array

So this is totally valid and clears the array:

 var numeros = [1,2,3,4,5]; numeros.length = 0; console.log(numeros);
Scroll to Top