Explain in detail about memory leaks in JavaScript?

Memory leaks in JavaScript

JavaScript is called garbage collected language,  that is when variables are declared, it will automatically allocate memory to them. When there are no more references for the declared variables, allocated memory will be released. Memory leaks or most of the memory related problems will occur while releasing the memory.

 Some common JavaScript leaks

 1) Accidental global variables

When a undeclared variable is referenced, javascript creates a new variable in the global object. In the following Example-1 let's say the purpose of languages is to only reference a variable in the "myArray" function. If we don't use var to declare it a global variable will be created. It may not do much harm, but the main problem arises when accidentally a global variable is created using "this" keyword that is as shown in Example-2.


function myArray(arg) {
   languages = "[javascript,.....]";  //  created using window


function myArray(arg) {
   this.languages = "[javascript,.....]";  // global object  

since,scope of the global variables never end, they remain in memory throughout the execution of the page even if they are not needed.That scenario makes garbage collector, which removes dynamic memory when a variable scope ends, to create a memory leakage(unused objects remaining in memory). The more the global variables, the more the memory leakage.

2) Closures

 A closure is an inner function that can access outer function’s variables (scope). Also, the inner function will continue to have access to the outer function’s scope even after the outer function is executed.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 below example, as all inner functions in a closure share the same context, innFun() shares the same context as "function() {}"  which is returned by the outer function. Now, for every 3ms we make a function call to outFun, a new value (after each call) is assigned  to a global variable  newvalue. As long a reference is pointing to this "function() {}", the shared scope is maintained and array is kept because it is part of the inner function(innFun) even if the inner function is never called. Each time we call outer function(outFun) we save the previous function(){} in the value(variable) of the new function. Therefore, again, the previously shared scope has to be kept. So in the nth call of the outer function(outFun), array of the (n-1)th call of outer cannot be garbage collected.This process stops once the memory runs out finally.


var newvalue;
function outFun() {
   var array = new Array(1000000);
   var value = newvalue;
      function innFun() {
        if (value) return array;
   return function () {};
setInterval(function () {
   newvalue = outFun();
   }, 3);