Removing all elements
suggest changelet 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:
let count = 0;
function addListener(data) {
const b = document.createElement("button");
b.id = "foo" + (count++);
document.body.appendChild(b);
b.addEventListener("click", function () {
console.log(data.length); // the listener keeps data alive
});
}
arr = ["big data"];
let i = 100;
while (i > 0) {
addListener(arr);
arr = []; // drops this binding, not the array the listener captured
arr.push("some large data");
i--;
}
// 100 arrays remain reachable from listeners. Replacing arr did not empty them.
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 length deletes every index from the new length up to the old one and keeps the same array object.
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
const keepArr = arr.splice(0); // empties the array and creates a new array containing the
// removed items