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?

0

2 Answers 2

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.

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

1 Comment

Nice to see different approaches. Why it is better to use [] notation than new Array().
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.

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.