You quite often read on the web that using closures is a massive source of memory leaks in JavaScript. Most of the times these articles refer to mixing script code and DOM e
You can find a good example and explanation in this blog post by David Glasser.
Well, here it is (I added a few comments):
var theThing = null;
var cnt = 0; // helps us to differentiate the leaked objects in the debugger
var replaceThing = function () {
var originalThing = theThing;
var unused = function () {
if (originalThing) // originalThing is used in the closure and hence ends up in the lexical environment shared by all closures in that scope
console.log("hi");
};
// originalThing = null; // <- nulling originalThing here tells V8 gc to collect it
theThing = {
longStr: (++cnt) + '_' + (new Array(1000000).join('*')),
someMethod: function () { // if not nulled, original thing is now attached to someMethod -> -> Closure
console.log(someMessage);
}
};
};
setInterval(replaceThing, 1000);
Please try it out with and without nulling originalThing
in Chrome Dev Tools (timeline tab, memory view, click record). Note that the example above applies to browser and Node.js environments.
Credit also and especially to Vyacheslav Egorov.