3 ms·
Garbage collection works by removing variables from memory when all references to a given variable are no longer available. The challenge is that a variable ca
by austincheney 8y ago
Garbage collection works by removing variables from memory when all references to a given variable are no longer available. The challenge is that a variable can out live the scope where it is declared.
//global variable
let closure;
{ // block
let x = function a (b) {
let c = b + 5;
return function (d) {
return d + c;
}
}
closure = a(5);
}
The variable named closure is in the global scope. The functions are long destroyed after the block closes. When does variable c get garbage collected? It is still needed by the global closure variable. All of that mess should be garbage collected when closure is garbage collected, but it can continue to live on as a different variable when used in an object or array.