2

Being a C developer, I feel the urgent need to free memory as accurately as possible. But after reading some posts about memory management in JavaScript I still have some questions about that topic. As far as I understand, there is a garbage collector that will automatically free the memory when an object isn't referenced anymore and the GC can find the time. So an object that is held in a local variable is very likely to be freed when the variable goes out of scope.

Let's assume I have some custom elements (tab control, data table, inputs etc.). The classes of those custom elements have member variables where several data for the specific element is stored. Also event listeners can be attached to the elements the custom element consists of.

Let's say I have following html markup:

<my-tabbar>
    <my-tab id="myTab">
        <my-input></input>
        <my-dataTable></my-dataTable>
    </my-tab>
</my-tabbar>

Now I want to remove <my-tab>. Is it sufficient to just do

var element = document.getElementById ("myTab");
element.parentNode.removeChild (element);
element = null;

Or do I have to dereference every object of the child elements and remove their event listeners?

Felix Dombek
  • 13,664
  • 17
  • 79
  • 131
sdrecker
  • 45
  • 7
  • I may be wrong but I suspect that memory management is something determined by implementations and not specifically mandated in ECMAscript specs. Thank God you've never had to code JavaScript for Internet Explorer 6. – Álvaro González Aug 13 '18 at 17:11

2 Answers2

1

It is sufficient to remove the element. You don't even have to set the variable to null afterwards – you can trust the JS engine to free the memory when it goes out of scope.

Felix Dombek
  • 13,664
  • 17
  • 79
  • 131
1

Setting an object to null makes it an empty object. Once the object is out of scope, the GC (when it runs) will clear it up. Setting local objects to null won't do you any good.

Example:

function whatever()
{
    var something = null;
    console.log( typeof( something ) );
}

whatever();

Output:

"object"

For the removal of a child node, please see this: Does removeChild really delete the element?

Source(s):

https://www.w3schools.com/js/js_datatypes.asp

cjriii
  • 344
  • 1
  • 10
  • That's very interesting. I did not know that null is an empty object in JavaScript. So if under any circumstances I have to manually dereference the variable that refers to the element I've removed (e.g. global variable) I would set the variable to undefined. – sdrecker Aug 14 '18 at 10:28