Does anonymous functions prevent variables from being destroyed by the garbage collector?


I will be using this HTML and JS DOM script as an example, to explain the problem:

<!DOCTYPE html>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <button id="my-button">Do Something</button>
    <script type="text/javascript">
        let setButtonFunc;

        setButtonFunc = function() {
            let button = document.getElementById("my-button");
            let phrase = "Printing Something";

            button.onclick = function() {
                text = document.createTextNode(phrase);
        setButtonFunc = null;


I defined a function setButtonFunc into a variable created with the let keyword. This function is used to set the button’s onclick property, enabling it to append text to the page every time its pressed.

My question is: will the variables phrase and button be collected by the Garbage Collector, once the variable setButtonFunc is set to null?

Logically, all their refereces vanish from that line. Once the variable is set to null, only the button’s onclick function should remain in memory. All the other variables should be collected by the garbage collector, as there are no other references to keep them alive out of scope.

However, if you keep pressing the button, the onclick function will keep executing normally as if phrase was never released from memory.

I just can’t seem to understand it. In python for example, if I were to execute this same example, there would be a time when the garbage collector would destroy the variable and an Exception would be raised.

Why doesn’t it happen here with Javascript? Is the anonymous function (used on button’s onclick) holding their references somehow? Am I missing something from the documentation?


Is the anonymous function (used on button’s onclick) holding their references somehow?

This is exactly what is happening and it is called hoisting

Answered By – Bqardi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published