How can closures cause memory leak and how to prevent it?


Closure

One of the strengths of javascript is closures. Javascript allows nested functions, a function inside a function, to access the variables of parent functions. This process of accessing outer function's variable by an inner function is called a closure. A memory leak occurs when a declared variable is automatically available to the inner nested function and resides in a memory despite it is not referenced in the inner nested function.

In the following example 'childFunction' is the inner function defined within the 'parentFunction' the outer function. When a call is made to 'parentFunction' with a parameter "outer val", the outer variable a is assigned the value of "outer val".The function returns with a pointer to the inner function "childFunction", which is contained in the variable 'val'.

The local variable a of outer function will still exist even though the outer function has returned. In javascript the moment parentFunction is called, a scope object with a property 'a' is created. This property contains the value of arg1, also known as "outer val". Similarly when the parentFunction returns, it will return the inner function(childFunction), which is contained in variable val.

Since the inner function holds a reference to a outer function's variables, the scope object with property 'a' will not be garbage collected. 

Example  

<html>
<body>
<script>
   window.onload= function parentFunction(arg1) {
      var a = arg1;
      return function childFunction (arg2)
   {
      alert( a +" "+ arg2);
   };
   };
   var val = parentFunction("outer val");
   val("inner val");
</script>
</body>
</html>

Avoiding memory leak

Adding one more function

By adding another function, there will be two inner functions. Since there are two inner functions, no function can refer outer function's variable there by halting closure altogether.

When there is no closure the chances of memory leakage will be less.

Example

Live Demo

<html>
<body>
<script>
   window.onload=function parentFunction(){
      var Obj1 = function childFunction1()
      {
         document.write("the leak is avoided");
      };
   (function childFunction2(){
      var obj2 = document.getElementById("closure");
      obj2.onclick=Obj1
      })();
   };
</script>
<input type = "button" id="closure" value ="Click Here">
</body>
</html>

Once the code executed a button will be displayed as follows

After pressing the button we will get the output as follows

Output

the leak is avoided

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements