Forgotten Callbacks, Getting a Closure

Robin Jangu

Posted On: April 12, 2018

view count24256 Views

Read time3 Min Read

Reason why JS is adored all over the internet is because of the powerful libraries and tools that empower us in making efficient web pages in very less time. Closure is one of the perks of JS which is used quite a lot. Now, every once while these commonly used phenomenons double cross the developers and fall prey to the dark side. In this blog we will understand how closures and callbacks result in memory leakage.

Closure and Callbacks

When you define any function in javascript, all the data in that parent function can be accessed by any other function that you define within the parent function’s boundaries. Closures provide you with associating the data and referencing to another function within.

The strongestavenger would display HULK, when you initiated the function strongestavenger. DisplayName() is the closure that has access to the name which stores HULK in it.

Callbacks as the name itself indicates are nothing but when a function and its components are called.

Callbacks and closures are basically work on the principle of referencing the data nodes for usage. So what will happen if these nodes are removed, or the data itself is deleted. Both of them will result in Memory leakage and will cripple the browser’s efficiency. DOM node referencing also works in the same manner and their effect is also the same.
Closures and with recursion if not properly used may easily handicap the browsers, mix it with a redundant variables and you have got a recipe for disaster.


Old versions of internet explorers had bugs due to which memory leakage due to forgotten callbacks and closures resulted in crashing. The problem then was that they couldn’t differentiate between javascript and DOM nodes cyclic differences. Even in the latest versions of the browsers today are not that efficient that they can reduce the memory leakage to zero. Till the time the node can be reached within the parent (window) function they can’t be swept by the garbage collection.

download whitepaper

It is impossible to not use closures while scripting, what can be done is keeping in check where the leakage is happening. Using browser profiling (mentioned in the memory debugging blog) time lapse we can easily detect the increase in memory. Find the root cause, what event or function is causing this surge and then explicitly delete them.

Especially if you are using jQuery, it is imperative that you don’t use eventlisteners too much. If you are writing script which requires events to be made, make events on list rather than making a list of events.

Author Profile Author Profile Author Profile

Author’s Profile

Robin Jangu

Robin is a Tech Blogger and Social Media Marketer.

Blogs: 19


Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free