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?

3
  • 5
    The answer/comment clearly mentions the problems. Commented Nov 8, 2013 at 18:32
  • Here are some methods to clear an array jsperf.com/array-destroy/40 Commented Nov 8, 2013 at 18:33
  • 1
    Rather than put a minus question you would have tried to understand the question... Commented Nov 8, 2013 at 18:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.