Last updated: April 15, 2022.
Method #1: Assign new value as
For example, a simple method for emptying an array is to reassign its value as
. Note that this method cannot be used for variables declared with the
/* Assigning a new value empties the array, but not previous references to it */ let pets = ["🐶","🐱","🐹"]; const petsCopy = pets; pets = ; console.log(pets); //  console.log(petsCopy); // ["🐶","🐱","🐹"]
Notice that the reference to the original array,
petsCopy, is now emptied using this method. If you want to clear the array and all previous references to it, there are some alternatives.
array.length = 0
Sometimes, things work, and we’re not sure why.
Setting the length property value of an array to 0 may seem like a bad hack, but it’s a valid way of emptying an array and all previous references to it. It even works for variables declared with
/* Setting the array length to 0 empties the array and all references to it */ const pets = ["🐶","🐱","🐹"]; const petsCopy = pets; pets.length = 0; console.log(pets); //  console.log(petsCopy); // 
If you want to use the most ‘correct’ method to empty an array and any references to it made in other variables, you should probably use splice.
The first two parameters of the splice method are the index at which to start deleting elements from the array, and the parameter the number of elements to delete.
So by passing in the index of the first array element (
array.length, you clear the array. And, splice will empty any references to the array made earlier in your code.
/* Deleting all array elements with splice also empties the array and all references to it */ const pets = ["🐶","🐱","🐹"]; const petsCopy = pets; pets.splice(0, pets.length); console.log(pets); //  console.log(petsCopy); // 
array.length = 0 VS
splice(0, array.length) both empty an array and prior references to it stored in other variables.
One decision criterion you might use to decide between these two methods is speed. Here is the result of a performance test we ran at JSBEN.CH:
It’s close, but the unconventional
array.length = 0 is slightly faster. And there is nothing to choose between them in terms of functionality.
Nevertheless, for the sake of future-proofing, it is probably safer to choose the more conventional option of
array.length = 0 solution no longer functional.
- MDN Web Docs: Array.prototype.splice