3
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!

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
qinHaiXiang
  • 6,051
  • 12
  • 47
  • 61
  • 4
    You answered your own question, at least the first one! – Stephen Aug 27 '10 at 16:17
  • possible duplicate of [How to empty an array in JavaScript?](http://stackoverflow.com/questions/1232040/how-to-empty-an-array-in-javascript) – Abid Rahman K Apr 25 '13 at 17:54
  • 1
    Possible duplicate of [How do I empty an array in JavaScript?](https://stackoverflow.com/questions/1232040/how-do-i-empty-an-array-in-javascript) – Mohammad Usman Nov 16 '17 at 08:06

8 Answers8

20

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);
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
4

the simple, easy and safe way to do it is :

arr.length = 0;

making a new instance of array, redirects the reference to one another new instance, but didn't free old one.

a.boussema
  • 1,096
  • 11
  • 19
2

one of those two:

var a = Array();
var a = [];
Johannes Weiss
  • 52,533
  • 16
  • 102
  • 136
2

Just as you say:

arr = [];
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
2

These are the ways to empty an array in JavaScript

  1. arr = [];
  2. arr.splice(0, arr.length);
  3. arr.length = 0;
0

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.

Stephen
  • 18,827
  • 9
  • 60
  • 98
0

Out of box idea:

while(arr.length) arr.pop();
0

Ways to clean/empty an array

  1. This is perfect if you do not have any references from other places. (substitution with a new array)

arr = []

  1. This Would not free up the objects in this array and may have memory implications. (setting prop length to 0)

arr.length = 0

  1. Remove all elements from an array and actually clean the original array. (splicing the whole array)

arr.splice(0,arr.length)

Ishan Garg
  • 571
  • 5
  • 13