var arr = [-3, -34, 1, 32, -100];

How can I remove all items and just leave an empty array?

And is it a good idea to use this?

arr = [];

Thank you very much!

share|improve this question
3  
You answered your own question, at least the first one! – Stephen Aug 27 '10 at 16:17

7 Answers

If there are no other references to that array, then just create a new empty array over top of the old one:

array = [];

If you need to modify an existing array—if, for instance, there's a reference to that array stored elsewhere:

var array1 = [-3, -34, 1, 32, -100];
var array2 = array1;

// This.
array1.length = 0;

// Or this.
while (array1.length > 0) {
    array1.pop();
}

// Now both are empty.
assert(array2.length == 0);
share|improve this answer
This is the answer. I wrote pretty much the same before spotting that John had already done it. – Tim Down Aug 27 '10 at 22:53

one of those two:

var a = Array();
var a = [];
share|improve this answer
arr = [] is recommended as it takes up less space (code wise). – Zoidberg Aug 27 '10 at 16:18
1  
And it is sexier. – Stephen Aug 27 '10 at 16:20
1  
@Stephen: [] turns you on? – BoltClock Aug 27 '10 at 16:21
1  
literally. ::drum-roll rim-shot:: – Stephen Aug 27 '10 at 16:24

Just as you say:

arr = [];
share|improve this answer

Using arr = []; to empty the array is far more efficient than doing something like looping and unsetting each key, or unsetting and then recreating the object.

share|improve this answer

While you can set it to a new array like some of the other answers, I prefer to use the clear() method as such:

array.clear();
share|improve this answer

The following article should answer part 2. http://stackoverflow.com/questions/864516/what-is-javascript-garbage-collection

share|improve this answer

Out of box idea:

while(arr.length) arr.pop();
share|improve this answer
Will work, but is needlessly inefficient. arr.length = 0 will be quicker and easier to read. – Tim Down Aug 27 '10 at 22:52

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.