0

Garbage Collector won't clear removed from DOM element if it has some reference in code. But what if this reference is inside attached to this element listener?

<span id="element">aga</span>
<script>
    function attach() {
        var element = document.getElementById("element");
        element.addEventListener("click", function() {
            //1) if element isn't used in this function
            console.log('aga');
            //2) if element is used in this function
            console.log(element);
        });
    }
    attach();

    document.body.innerHTML = '';
</script>       
Slavik
  • 6,647
  • 3
  • 15
  • 18

1 Answers1

0

If garbage collection is "properly" implemented by the browser (in particular if it uses Mark-and-sweep algorithm), that DOM element should be collected, as it is now unreachable from global scope.

Your question is probably related to the cyclic reference leading to potential memory leak when the GC implementation uses just a reference counting algorithm. Refer to the above link for more details.

You may also be interested in this post: What is JavaScript garbage collection?

Community
  • 1
  • 1
ghybs
  • 47,565
  • 6
  • 74
  • 99