When you want to empty an array but don’t have no idea how to empty it. You have come to the right place, in this blog I’m going to share with you a few ways to empty an array in JavaScript.
Before I start, at first all you need to have an array. Let’s say you have the array like below that would like to empty it.
const array = ['a','b','c','d','e'];
Method 1: array.length
You can clear the array by setting the .length
of the array to 0. The array will be empty straight away. I always use this in the past, now 2020 seems like .splice()
is faster.
array.length = 0;
Method 2: array.splice() ????
When you use splice()
, it will return the original array and remove all of it. No worries, it doesn’t impact any performance when you splice()
. It’s now one of the fastest method to empty the array in 2020.
array.splice(0);
Method 3: Overwrite Array with [] ????
The third method is very fast but not recommended because there are some problem of overwrite the array with the new empty array []
.
Problem
const array2 = array; // Reference array by another variable
array = []; // Overwrite the array with []
console.log(array2); // The Output of array2 still same ['a','b','c','d','e'];
Method 4: While Loop with pop()
Removing one element in the array every single loop seems not efficient. Unfortunately the performance doesn’t works well.
while(array.length > 0) {
array.pop();
}
Method 5: While Loop with shift()
This method is extremely slow, I recommend skip this one. I’m writing it here just to let you know there are another method to empty the array in case you asked.
while (array.length > 0) {
array.shift();
}
Conclusion
Compared to others method, the first and second are the much more better than other method to empty an array. We recommend of using the .length
or .splice()
. The technologies keep changing, the performance of the method can be change. I recommend you to test the performance at here before you use.