3

I read the topic How do I empty an array in JavaScript?

Answer :

Very simple:

A = [];

I am interested in the comment by Daniel Baulig:

this will NOT empty the array, but create a new, empty array. This might cause problems, especially if there are other references to the array. OP: Please consider to accept Matthew's answer instead. It is the cleaner and formally correct approach. – Daniel Baulig Jan 19 '11 at 13:08

Can you tell me what problems this could cause?

Community
  • 1
  • 1
Michael Phelps
  • 3,451
  • 7
  • 36
  • 64

1 Answers1

9

The problem is that you may have another reference to that array.

Consider this :

var A = ['A'];
var B = A;

If you do

A = [];

this will still let B be ['A']. That's the difference between emptying (or changing) an array, or replacing it (what you did).

When you do

A.length=0;

then B will be empty too.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758