I will be using this HTML and JS DOM script as an example, to explain the problem:
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
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.
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