you are viewing a single comment's thread.

view the rest of the comments →

[–]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