CoderBear's Blog
Memory leaks in JavaScript II
July 1, 2015

Reference counting
A very naive garbage collection alogrithm is Reference Counting. In this method, the number of references to each object is tracked. If this number is 0, it means no other object is referring to it, it is not being used and hence no longer needed. It can now be garbage collected. However, this method fails when it comes to handling circular references.

What is a circular reference?
If an element A is pointing to element B, and B in turn is point directly, or indirectly to A, we have a circular reference. The reference count of neither of these elements will never be 0, and so they shall never be garbage collected. Below is an example of a circular reference in all its simplicity.

Note : No modern day browser implements Reference Counting. Garbage collectors now use variants of Mark and sweep (explained in the previous post) and are smart enough to detect and handle circular references. However, IE 6 and 7 had serious memory leaks caused by circular references. While the number of people still using IE 6/7 is extremely low, it is informative and interesting to understand such leaks and the way around them.

JS Bin on

elem points to someElement in the DOM, and someElem's property in turn points to elem. The reference count for neither of them will never be 0, and they wont be garbage collected. The property someData serves only to show that this memory leak might as well be an expensive one owing to the large size of the object causing the leak.

Circular references and closures
Closures are common in JavaScript and are often a source of memory leaks. Consider the snippet below.

JS Bin on

elem points to an element in the DOM. The onclick function on elem is a closure in reference to the outerFunction. Because innerFunction is a closure, it has access to the outer variable someData, and it is this implicit reference that creates a circular reference i.e, elem points to the DOM, and the onclick or the innerFunction function on the DOM elemement (which is a closure), points to someData, which is a part of elem.

Such code slips are quite simple and common, and in the days of IE 6/7 were quite capable of wreaking havoc on the memory given the right environment.

In the next post, we shall see what are the different ways to break/avoid circular references.

Feel free to get back to me with any doubts or clarifications. I shall try my best to answer each one of them personally.

Receive my blogs in your email. Subscribe.

Only Javascript. No Spam. Promise.