@tkinson

« Back to blog

Javascript closure memory leak

The foillowing is an excerpt from the Google JavaScript style guide:

The ability to create closures is perhaps the most useful and often overlooked feature of JS.

One thing to keep in mind, however, is that a closure keeps a pointer to its enclosing scope. As a result, attaching a closure to a DOM element can create a circular reference and thus, a memory leak. For example, in the following code:

function foo(element, a, b) {
  element.onclick = function() { /* uses a and b */ };
}

the function closure keeps a reference to element, a, and b even if it never uses element. Since element also keeps a reference to the closure, we have a cycle that won't be cleaned up by garbage collection. In these situations, the code can be structured as follows:

function foo(element, a, b) {
  element.onclick = bar(a, b);
}

function bar(a, b) {
  return function() { /* uses a and b */ }
}

I expect this is by far the most commonly made Javascript memory leak.