Reputation: 7812
I am dynamically adding a 'div' node inside a function that will only be needed temporarily. I have already used < parent >.removeChild to detach it and then set it to null, but I am curious to know what happens to unattached nodes created in a function when it goes out of scope?
If the nodes remain in memory but unattached:
Here is an example function for discussion purposes:
function dpi(){
var res={},
div=document.createElement("div"),
body=document.getElementsByTagName('body')[0];
div.style.position="absolute";
div.style.width="1in";
div.style.height="1in";
div.style.left="-100%";
div.style.top="-100%";
body.appendChild(div);
res["xdpi"]=div.offsetWidth;
res["ydpi"]=div.offsetHeight;
body.removeChild(div);
div=null;
return res;
}
Upvotes: 1
Views: 1187
Reputation: 129109
JavaScript uses automatic memory management. That is, it uses a garbage collector, where anything that's not referenced will be freed up automatically. To answer your specific questions:
null
— it'll go away when you return.I should note that some older browsers have reference-counting implementations of garbage collectors, where if you have cycles (an element pointing to something else pointing back to the element, which often occurs in event listeners), they may not be collected and you'd have to break the reference explicitly, but most browsers today are smarter.
Upvotes: 2
Reputation: 324760
The garbage collector, when it runs, will seek out anything that is not connected to anything else (roughly - it has some special stuff to handle circular references that aren't connected to other things). Basically, if there is no more variable pointing to the element, it will be removed from memory at the browser's convenience. Now, that might be instant, or it might be when the browser arbitrarily decides it's using too much memory and decides to clean up a bit. I don't believe there is any specification on how the browser should garbage collect.
Upvotes: 1