Ways to clear an existing array in Javascript
There are some ways to empty an existing array in Javascript.
1. Init array
A = [];
This code will set the variable A
to a new empty array. This is perfect if you don't have references to the original array A
anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A
.
This is also the fastest solution.
This code sample shows the issue you can encounter when using this method:
var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1; // Reference arr1 by another variable
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']
2. Using splice method
A.splice(0, A.length)
Using .splice()
will work perfectly, but since the .splice()
function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.
var arr1 = ['a','b','c','d','e','f'];
var result = arr1.splice(0, arr1.length);
console.log(result); // Output ['a','b','c','d','e','f']
3. Using the length property
A.length = 0
lenght is an instance property of Array
, it returns or sets the number of elements in an array. You can set the value of the length property to truncate the array. When setting to 0, you can clear the array.
var arr = ['a','b','c','d','e','f'];
arr.length = 0;
console.log(arr); // Output []
4. With pop method
while(A.length > 0) {
A.pop();
}
This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.
var arr = ['a','b','c','d','e','f'];
while(arr.length > 0) {
arr.pop();
}
console.log(arr); // Output []