Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, what's the difference between myArray.length = 0 vs myArray = new Array()? [duplicate]

Tags:

javascript

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?

like image 393
Aaron Avatar asked Sep 03 '13 11:09

Aaron


People also ask

Is empty array length 0?

Using the length propertyIf the length of the array is 0, then the array is empty otherwise it is not empty.

How to define array length in js?

One common way of creating an Array with a given length, is to use the Array constructor: const LEN = 3; const arr = new Array(LEN); assert.

How do you find the length of an array in typescript?

To get array length in typescript, just use Array. length it will count and return numbers of element.


1 Answers

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.

like image 181
Joon Avatar answered Nov 11 '22 15:11

Joon