Memory life cycle in JavaScript may be described as:

  1. allocating the memory for the objects, properties …, 
  2. using the memory (explicitly done by programmers) and
  3. releasing the memory when used (implicitly done).

By declaring variables and initializing it, cache memory gets is allocated to it. When a value is written and read, variables are said to be used. Some examples of memory allocation and initialization are listed below:

Example of memory allocation and initialization

var num = 123;
    var obj = {
        a: “Name”,
        b: 124
};
var arr = [63, 67,”North America”, null];
function f(num){
    return num+2;
}
var Lion  = new Animal();
var para = document.createElement(“div”);
var str1 = “Washington”;
var str2 = str1.substr(5, 3);

When a value is no more referenced in the script, memory is freed through garbage collection. More information on garbage collectors and its algorithms are given in its reference section.

When writing long JavaScript programs, care should be taken to optimize it for memory. Programs should run effectively in most of the JavaScript engines of popular browsers. However, optimization should not be harmful for the functioning of code or memory. 

Memory leaks are an issue in browser applications. It occurs due to gradual loss of the available memory, when memory is allocated to an object and garbage collection fails to retrieve repeatedly. Keeping references of DOM elements which are not used, binding event listeners even when not using and large chunk of data left without garbage collected due to circular reference are few reasons for memory leak. Memory leaks can be detected using timeline memory view of browser debugging window such as Chrome. 

Example of memory leak

/*Sample code of memory leak due to Closure. */
function func(){
    var data = BigInteger(“Large Data”);
    function innerFunc(){
        //……
}
return innerFunc;
}

When innerFunc stays in the memory, the lexical environment stores the BigInteger data though it is not in use. Multiple calls of innerFunc lead to a large chunk of unused data stored in the memory, leading to memory loss.

 

›› go to examples ››