-1

I have a short question, just out of curiosity. Let's say I have an object which has an array as a property this.arr = ["one", "two", "three", ...], and I populate this array with n elements.

What will happen to all these elements if I run this.arr = [] . Are they deleted, kept in memory, leaked?

Thanks!

Jo Colina
  • 1,870
  • 7
  • 28
  • 46
  • 1
    Possible duplicate of [How to free up the memory in JavaScript](http://stackoverflow.com/questions/8467350/how-to-free-up-the-memory-in-javascript) – felipsmartins Nov 03 '15 at 14:02
  • Read: [Javascript Memory Management](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management) – felipsmartins Nov 03 '15 at 14:03
  • Possible duplicate of [How to empty an array in JavaScript?](http://stackoverflow.com/questions/1232040/how-to-empty-an-array-in-javascript) – Nina Scholz Nov 03 '15 at 14:10

4 Answers4

2

this.arr = [] will create a new empty array and assign it to the arr property. If there is no more reference to the previous array in the program, it will be garbage collected eventually (automatically destroyed by the JS engine). But if there is still a reference to it somewhere, it will still exist.

this.arr = [1, 2, 3, 4];
var backup = this.arr;
this.arr = [];
// backup still points to the array, so it won't be destroyed

If you just want to delete an array as you won't use it anymore, you could do this.arr = null instead.

In JS, there is no such thing as "memory leaks". You can, however, forget to get rid of an object you don't need anymore. And if that object has references to other objects which in term have references to other objects, than not a single object of the tree will get destroyed.

Most of the time, if you use temporary variables, you won't need to worry about it.

Domino
  • 6,314
  • 1
  • 32
  • 58
0

They are deleted. As a matter of fact this is a fast way to empty an array.

pinturic
  • 2,253
  • 1
  • 17
  • 34
0

It would be deleted. If you assign the value of this.arr to another variable, the array would be reusable, but the other variable would have different memory address, but the address, you stored the original variable would be emptied.

Krisztián Dudás
  • 856
  • 10
  • 22
0

They will be deleted, If the string objects are no longer referenced by anything. The string objects are therefor eligible for the garbage collection to delete/release these objects.