Computer >> Computer tutorials >  >> Programming >> Javascript

Eradicating Memory Leaks in Javascript


The main cause for leaks in garbage collected languages are unwanted references. To understand memory leaks, let us see how the memory freeing(garbage collection) works.

Mark-and-sweep algorithm −This algorithm reduces the definition of "an object is no longer needed" to "an object is unreachable". This algorithm assumes the knowledge of a set of objects called roots. In JavaScript, the root is the global object. Periodically, the GC starts from these roots, find all objects that are referenced from these roots, recursively. Starting from the roots, the GC will thus find all reachable objects and collect all non-reachable objects.

Types of memory leaks

1. Global variables(undeclared/accidental)

In JS, you can declare a variable globally accidently if you do not specify a declaration keyword(let, var, const). JS looks up moving out in scope until it reaches global scope and if it doesn't find the variable in any scope, it creates a global variable.

Example

function test() {
   a = [1, 2, 3]
}
test()
// a was initialized without declaration using a keyword and is now in the global scope.
console.log(a)

Output

[1, 2, 3]

This behavior can cause memory leaks as variables are unknowingly present in the global scope and wont be freed unless the program ends. This can be fixed by using a declaration keyword.

2. Closures

A memory leak occurs in a closure if a variable is declared in the outer function and it becomes automatically available to the nested inner function and continues to be in memory even if it is not being used/referenced in the nested function.

3. Detached DOM/Out of DOM Reference

DOM is a doubly-linked tree, having reference to any node in the tree will prevent the entire tree from garbage collection. Detached DOM or Out of DOM reference means that the nodes which have been removed from the DOM but are in memory through JS. It means that as long as there’s still a reference to a variable or an object anywhere, that object isn’t garbage collected even after being removed from the DOM. Always remove reference from JS once you're done with part of DOM.

4. Event Listeners

The addEventListener() method attaches an event handler to an element and multiple event handlers can be added to a single element. If a DOM element and its event listener don’t have the same lifecycle, it could lead to a memory leak.