10

Regarding JavaScript, when clearing an array, I've found two methods:

myArray.length = 0;

vs

myArray = new Array()

I would guess myArray.length = 0; keeps the reference while myArray = newArray() creates a new reference making previous references void.

What's the difference (if any) between the two methods?

Aaron
  • 3,195
  • 5
  • 31
  • 49

2 Answers2

6

You are correct this time. new Array() creates a new instance of array and assign it to myArray. myArray.length = 0 empties an old array while myArray still points to the old array.

Btw, it is better to use [] notation than new Array().

I personally always try to use myArray.length = 0; since it actually empties the content of the array.

Joon
  • 9,346
  • 8
  • 48
  • 75
0
myArray.length = 0; // Signifies empty array
[1,2,3] // Length of this array is 3

So basically, an array with content is overwritten with an empty array.

You can also use this:

myarray = []; //More simple and elegant!!!

Performance wise: [] is faster than new Array();

As juno already said: new Array() creates a new instance of the array (this array will be of the size mentioned in arguments) and assigns it to myArray.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
HIRA THAKUR
  • 17,189
  • 14
  • 56
  • 87