Questions And Answers

More Tutorials

Javascript Removing all elements

var arr = [1, 2, 3, 4];

Method 1

Creates a new array and overwrites the existing array reference with a new one

arr = [];

Care must be taken as this does not remove any items from the original array. The array may have been closed over when passed to a function. The array will remain in memory for the life of the function though you may not be aware of this. This is a common source of memory leaks.

Example of a memory leak resulting from bad array clearing:

var count = 0;
function addListener(arr) { // arr is closed over
 var b = document.body.querySelector("#foo" + (count++));
 b.addEventListener("click", function(e) { // this functions reference keeps
 // the closure current while the
 // event is active
 // do something but does not need arr
arr = ["big data"];
var i = 100;
while (i > 0) {
 addListener(arr); // the array is passed to the function
 arr = []; // only removes the reference, the original array remains
 array.push("some large data"); // more memory allocated

To prevent the risk of a memory leak use the one of the following 2 methods to empty the array in the above
example's while loop.

Method 2

Setting the length property deletes all array element from the new array length to the old array length. It is the most efficient way to remove and dereference all items in the array. Keeps the reference to the original array

arr.length = 0;

Method 3

Similar to method 2 but returns a new array containing the removed items. If you do not need the items this method is inefficient as the new array is still created only to be immediately dereferenced.

arr.splice(0); // should not use if you don't want the removed items
// only use this method if you do the following
var keepArr = arr.splice(0); // empties the array and creates a new array containing the
 // removed items


In this page (written and validated by ) you learned about Javascript Removing all elements . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript Finding the minimum or maximum element.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.