Modern engines would not maintain unused variables in the outer scope.
Therefore, it doesn't matter if you set data = null
before returning the inner function, because the inner function does not depend on ("close over") data
.
If the inner function did depend on data
--perhaps it returns it--then setting data = null
is certainly not what you want to, because then, well, it would be null instead of having its original value!
Assuming the inner function does depend on data
, then yes, as long as inner
is being pointed to (referred to by) something, then the value of data
will have to be kept around. But, that's what you are saying you want! How can you have something available without having it be available?
Remember that at some point the variable which holds the return value of f()
will itself go out of scope. At that point, at least until f()
is called again, data
will be garbage collected.
The general rule is that you don't need to worry about memory and leaks with JavaScript. That's the whole point of GC. The garbage collector does an excellent job of identifying what is needed and what is not needed, and keeping the former and garbage collecting the latter.
You may want to consider the following example:
function foo() {
var x = 1;
return function() { debugger; return 1; };
}
function bar() {
var x = 1;
return function() { debugger; return x; };
}
foo()();
bar()();
And examine its execution in Chrome devtools variable window. When the debugger stops in the inner function of foo
, note that x
is not present as a local variable or as a closure. For all practical purposes, it does not exist.
When the debugger stops in the inner function of bar
, we see the variable x
, because it had to be preserved so as to be accessible in order to be returned.
Does this hold true today? Or is this article outdated?
No, it doesn't, and yes, it is. The article is four years old, which is a lifetime in the web world. I have no way to know if jQuery still is subject to leaks, but I'd be surprised if it were, and if so, there's an easy enough way to avoid them--don't use jQuery. The leaks the article's author mentions related to DOM loops and event handlers are not present in modern browsers, by which I mean IE10 (more likely IE9) and above. I'd suggest finding a more up-to-date reference if you really want to understand about memory leaks. Actually, I'd suggest you mainly stop worrying about memory leaks. They occur only in very specialized situations. It's hard to find much on the topic on the web these days for that precise reason. Here's one article I found: http://point.davidglasser.net/2013/06/27/surprising-javascript-memory-leak.html.