Wednesday, 6 December 2017

JavaScript | How to empty an array in JavaScript?

For instance, we have an arrayList,
var arrayList =  ['a','b','c','d','e','f'];

There are a couple ways we can use to empty an array, so let's discuss them all.

Method 1
arrayList = [];
This code will set the variable arrayList to a new empty array. This is perfect if you don't have references to the original array arrayList anywhere else because it will actually create 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 arrayList.

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']

Method 2
arrayList.length = 0
The code above will clear the existing array by setting its length to 0. This way of emptying the array also updates all the reference variables that point to the original array. Therefore, this method is useful when you want to update all reference variables pointing to arrayList.

For Instance,
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 implementation above will also work perfectly. This way of emptying the array will also update all the references to the original array.
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 > 0) {
    arrayList.pop();
}
This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.

Performance

Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...