Objects in Javascript get garbage collected when they lose scope and are no longer referenced. However, when is an element not referenced anymore? Take the following IIFE below:
var el = (function() {
// Generate DOM element, but don't attach it to DOM
var div = document.createElement('div');
// Provide interior content
div.innerHTML = '<span>A</span><span>B</span>';
// Get reference to first child element in div
var result = div.firstChild;
// Blow away all div content
div.innerHTML = '';
// Return original first child element
return result;
})();
My question is twofold:
- Does removing the content in the
div.innerHTML = '';assignment also remove the references to any child nodes inside of it, or is it done so later during pre-memory retrieval of the garbage collection process? - If the
divhad been attached to the DOM instead of a local variable that went out of scope as the function exited, would it make any difference?