Arrays are widely and commonly used in JavaScript. Especially if you are developing a dynamic app, there are very high chances that you might use Arrays in JavaScript. However, many a times I’ve noticed that people don’t use the Array related methods properly and end up doing certain things in a wrong way. One such example is, how to remove all items from array in javascript .
While there are various solutions available over the internet, I believe the following approach is good enough for most of the scenarios.
How to Clear or Empty an array in JavaScript ?
One of the most common ways people use to clear an Array in JavaScript is by assigning it a blank value. For e.g someArray = []
. This is a bad way to empty an array in JavaScript because it would technically create a new array. Instead, you should ideally set the length of the array to zero like :
someArray.length = 0;
Setting the length of an Array to zero would clear the existing array and avoids creating a new array. This would be helpful especially if you had a reference to the old array in some other array variable . For e.g :
Array_A = ['Green','Blue','Red','Yellow'];
Array_B = Array_A;
Array_A = [];
console.log(Array_B) // Prints ['Green','Blue','Red','Yellow']
/* Better way to do it. */
Array_A = ['Green','Blue','Red','Yellow'];
Array_B = Array_A;
Array_A.length = 0;
console.log(Array_B); // Prints []
Hope you found this article helpful. Please do like us on facebook and follow us on Twitter.