JavaScript arrays are commonly used by developers and making them empty is also used in practice. Here I am describing 4 ways to empty an array in JavaScript:
Method I – Use splice() method
1 | myArray.splice(0, myArray.length) |
splice() method is built in function for array in JavaScript and using it will work perfectly but this function will actually return a copy of original array or an array with all the removed items. Hence it’s not enough efficient.
Method II – Set length to zero
1 | myArray.length = 0 |
Setting length to zero will clear the existing array. The length property of an array is a read/write property so it works well and also when using “strict mode” in Ecmascript 5.
Method III – Using pop() method
1 2 3 | while(myArray.length > 0) { myArray.pop(); } |
This solution might look lengthy but it is by far the faster solution (apart from set array to new empty array). Use pop() method in while loop if you are curious about performance. This is faster than using splice() method or setting length to zero.
Method IV – Set array to new empty array
1 | myArray = []; |
if you don’t have references to the original array then setting the variable myArray to a new empty array is the perfect solution for you. Because this solution actually creates a brand new (empty) array. It’s the fastest solution and be careful and use this only if you only reference the array by its original variable.
There were generally available solutions to empty an array in JavaScript and share your opinions and the methods you use to clear an array.
How about arr = new Array()?
There are five most of the way to empty an array as below:
var arr = [1,2,3,4,5]
1. arr = []
2. arr.length = 0;
3. arr.splice(0);
4. arr = arr.constructor();
5. while(arr.length>0){
arr.pop();
}
Thanks @ra@raovasimakramrana:disqus for no #4 :p
You welcome Amit !!
Thanks your blog helped me a lot