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 thought it would be 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 cleared:
Also using the method
splice()
that removes from the original array and returns the elements in the specified range. So you would have another instance of an array:Also using the JavaScript method
pop()
that removes the last element of the array . So to clean it completely you would have to execute the methodpop()
for each element of the array :And finally assigning 0 to the property
length
. According to the documentation :So this is totally valid and clears the array:
There are 4 methods to clean an array.
Method 1
This is the Optimal method but you have to be careful because you lose the reference of the original array, and if the variable is of type
const
you could have errors.Method 2
This will delete the existing array by setting its length to
0
. Some have argued that this may not work in all JavaScript implementations, but it turns out this is not the case. It also works when using " strict mode " inECMAScript 5
because the length property of an array is oneread/write
that allows you to override the value.Method 3
This function will return an array with all elements removed, and will also return a copy of the original array.
Method 4
It is not very common and as you will see you will also have a low performance.
Which one has the best performance? Of all the methods, the clearest way to flush an array is methods 2 and 3 which are very similar in performance and faster than method 4. see this Benchmark
Well, a simple way to remove it would be:
The correct and simple way to delete the content of an array or rather to empty it is: