How does garbage collection work in JavaScript?
While some details about garbage collection vary between JS engines, the basic rule is that objects are eligible for garbage collection when there are no longer any references to them anywhere. So for instance, if you declare a variable inside a simple function like the following, then the variable may be garbage collected at any time after the function returns. 1 2 3 function myFunc() { var foo = ‘bar’; } However, variables declared in the global scope will have global references for the lifetime of the script (eg. until the document is unloaded). A slight complication is introduced by “closures”, demonstrated here: 1 2 3 4 5 6 function outerFunc() { var foo = ‘bar’; return function () { return foo; } } In the above example, var foo gets created when outerFunc() is called, but because outerFunc returns another function that has access to foo as part of its context, foo cannot be garbage collected until there are no longer any references to the *inner* function (ie the return value of