Tuesday, 15 May 2018

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





Regarding JavaScript, when clearing an array, I've found two methods:



myArray.length = 0;


vs



myArray = new Array()



I would guess logically myArray.length = 0; keeps the reference while myArray = newArray() creates a new reference making previous references void.



However, I have found in the past guessing how JavaScript works by using my own logic has been regularly unsuccessful :)



What's the difference (if any) between the two methods?


Answer



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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...