It is possible to empty an array in a few different ways, so let’s go over every method that is available.
Let’s say you want to get eliminate of every entry in the following array:
var arrayList = ['a', 'b', 'c', 'd', 'e', 'f'];
Method 1
arrayList = [];
The above code will create a fresh, empty array for the variable arrayList. Since it will truly generate a new empty array, using this is advised if you don’t have references to the original array arrayList somewhere else.
If you reference this array from another variable, the original reference array will remain unaltered, therefore you should use caution when emptying the array in this manner. Use this method only if the array has only been referred to by the original variable arrayList.
var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array var anotherArrayList = arrayList; // Referenced arrayList by another variable arrayList = []; // Empty the array console.log(anotherArrayList); // Output ['a', 'b', 'c', 'd', 'e', 'f']
Method 2
arrayList.length = 0;
By setting the length of the existing array to 0, the code above will clear it. All the reference variables that point to the original array will be updated as a result of this method of emptying an array.
For example:
var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array var anotherArrayList = arrayList; // Referenced arrayList by another variable arrayList.length = 0; // Empty the array by setting length to 0 console.log(anotherArrayList); // Output []
Method 3
arrayList.splice(0, arrayList.length);
The previous implementation will equally well. The references to the original array will all be updated if you empty the array in this way.
var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array var anotherArrayList = arrayList; // Referenced arrayList by another variable arrayList.splice(0, arrayList.length); // Empty the array by setting length to 0 console.log(anotherArrayList); // Output []
Method 4
while(arrayList.length) { arrayList.pop(); }
The array can also be empty using the aforementioned technique. But frequent use is not advised.