Difference between Array.length = 0 and Array =[]?

foo = [] creates a new array and assigns a reference to it to a variable. Any other references are unaffected and still point to the original array.

foo.length = 0 modifies the array itself. If you access it via a different variable, then you still get the modified array.

Read somewhere that the second one creates a new array by destroying all references to the existing array

That is backwards. It creates a new array and doesn’t destroy other references.

var foo = [1,2,3];
var bar = [1,2,3];
var foo2 = foo;
var bar2 = bar;
foo = [];
bar.length = 0;
console.log(foo, bar, foo2, bar2);

gives:

[] [] [1, 2, 3] []

arr.length =0;// expected to empty the array

and it does empty the array, at least the first time. After the first time you do this:

arr = arr + $(this).html();

… which overwrites the array with a string.

The length property of a string is read-only, so assigning 0 to it has no effect.

Leave a Comment