🧠 Memory leaks and Garbage Collection 🗑️ in JavaScript.

You should know this

<Andrew Rymaruk />
Oct 12, 2019 · 6 min read

Memory leaks are a problem every developer has to face eventually.

What are memory leaks?

In essence, memory leaks can be defined as memory that is not required by an application anymore that for some reason is not returned to the operating system or the pool of free memory.

Of course, you can favor different ways of managing memory, and these ways may reduce the chance of leaking memory.

However, whether a certain piece of memory is unused or not is actually an undecidable problem.

Memory Management && Memory Life Cycle In Javascript 👇

We define various primitives, objects, functions, etc. in our program. When we do, the JavaScript engine assigns them a space in the main memory of the device. Different browsers have different techniques to manage their data.

Memory Life Cycle In the high-level language, We will just read and write to the memory explicitly (Use Memory). In the low-level language, all three steps the developer needs to take care of explicitly.

Allocate memory to the variables.

Use the defined variables.

Remove them from the memory.

The reason why we need to understand the concept of memory management while learning any programming language is to prevent memory leaks.

In any program, memory leaks may lead to several problems, including slow execution, program crashing, high latency (large delays in processing the data), etc.

💡 The most important task in managing memory is to detect the unused variables in a program and remove them from memory.

When declaring the variable, Javascript will automatically allocate the memory for the variables

When the memory is no longer needed anymore, then the allocated memory will be released. Memory leak and most of the memory-related issues come while releasing the memory. The hardest part is finding the memory which is no longer needed and it is tracked down by the garbage collector.

Garbage Collector 👇

The main cause for leaks in garbage collected languages are unwanted references.” via @auth0 http://auth0.com/blog/four-types-of-leaks-in-your-javascript-code-and-how-to-get-rid-of-them/

JavaScript uses Garbage Collector to decide whether a piece of code requires memory or not. Most garbage collectors use an algorithm known as mark-and-sweep.

In simple terms, the algorithm “mark-and-sweep” consists of the following steps:

1️⃣ The garbage collector builds a list of “roots”.

Roots usually are global variables to which a reference is kept in code. The window object is always present, so the garbage collector can consider it and all of its children to be always present (i.e. not garbage).

2️⃣ All roots are inspected and marked as active.

All children are inspected recursively as well. Everything that can be reached from a root is not considered garbage.

3️⃣ All pieces of memory not marked as active can now be considered garbage.

The collector can now free that memory and return it to the OS.

Modern garbage collectors improve on this algorithm in different ways, but the essence is the same: reachable pieces of memory are marked as such and the rest is considered garbage.

The Three Types of Common JavaScript Leaks

👉 Accidental global variables

One of the ways in which JavaScript is permissive is in the way it handles undeclared variables: a reference to an undeclared variable creates a new variable inside the global object.

In the case of browsers, the global object is a “window”. For instance:

but, is in fact

If bar was supposed to hold a reference to a variable only inside the scope of the someFn function and you forget to use var to declare it, an unexpected global variable is created.

To prevent these mistakes from happening, add 'use strict'; at the beginning of your JavaScript files. This enables a stricter mode of parsing JavaScript that prevents accidental globals.

👉 Forgotten callbacks or timers

The use of setInterval is quite common in JavaScript. Most of libraries provide observers and other facilities that take callbacks.

The example below illustrates what can happen with dangling timers: timers that make reference to nodes or data that is no longer required.

The object represented by node maybe removed in the future, making the whole block inside the interval handler unnecessary. However, the handler, as the interval is still active, cannot be collected (the interval needs to be stopped for that to happen).

If the interval handler cannot be collected, its dependencies cannot be collected either. That means that, someResource which presumably stores sizable data, cannot be collected either.

For the case of observers, it is important to make explicit calls to remove them once they are not needed anymore

Frameworks and libraries such as jQuery e.t.c do remove listeners before disposing of a node.

This is handled internally by the libraries and makes sure that no leaks are produced, even when running under problematic browsers such as 🎃 the old Internet Explorer.

👉 Out of DOM references

Sometimes it may be useful to store DOM nodes inside data structures.

Suppose you want to rapidly update the contents of several rows in a table. It may make sense to store a reference to each DOM row in a dictionary or array.

When this happens, two references to the same DOM element are kept: one in the DOM tree and the other in the dictionary.

If at some point in the future you decide to remove these rows, you need to make both references unreachable.

If you enjoyed this article, please share it with your developer friends and in social media.

JavaScript in Plain English

Learn the web's most important programming language.

<Andrew Rymaruk />

Written by

✅ CIW JavaScript Specialist 🚀I love JS programming and coffee ☕ I'm ready for the next challenge ;) http://rymaruk.com

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade