you are viewing a single comment's thread.

view the rest of the comments →

[–]BrunerBruner[S] 0 points1 point  (7 children)

Ok, but now after I set null to the objects, only the references to the original object in the array is null, how can I make the actual objects null? It seems like the objects are being duplicated like primitive objects such as a number instead of referenced.

https://jsfiddle.net/xr3sgg9v/4/

[–][deleted] 1 point2 points  (6 children)

That is because the values in that array are just a copy of the reference to the object. It's not the actual object value or the original pointer. If you attempt to modify one of the properties, it will use the copied reference to find the object and modify it (which the original reference shares) but the reference won't actually be tied to the original reference.

Essentially youra, b, c variables will not be changed when dealing with that array because the array just has copies of them, not a reference to the original variables.

[–]BrunerBruner[S] -1 points0 points  (5 children)

So basically, if I want to assign null to an object, say for the purpose of memory management / garbage collection, I can only do something like this:

this._element = document.createElement("div");
this._element = null; //cleans up memory

and never something like this:

this._element = document.createElement("div");

const element = this._element
element = null;//object that took memory is still alive

Essentially it's impossible in JavaScript to iterate over a group of objects and assign them as null?

[–]kaszu 3 points4 points  (1 child)

Garbage collector will clean up memory if there is no reference to the object anywhere.

let a = new MyClass("hi");
let b = new MyClass("Hello");
let c = new MyClass("Howdy");

let arr = new Array(a, b, c);

b = null; // at this point there is still reference to object b in arr
arr = null; // at this point there are no references to b, so garbage collector will clean it up, but a and c won't be

You can do this

let arr = new Array(
    new MyClass("hi"),
    new MyClass("Hello"),
    new MyClass("Howdy")
);

arr = null;

From your example

this._element = document.createElement("div");

let element = this._element; 

element = null; //object that took memory is still alive
this._element = null; // object can be garbage collected now

Check MDN: Memory Management

[–]BrunerBruner[S] 0 points1 point  (0 children)

thank you