JavaScript Garbage Collection – Unravel it with Diagrams & Examples

Free Web development courses with real-time projects Start Now!!

Garbage collection is essential to learn for those who want to master any programming language, including JavaScript. The concept of memory management is one of those advanced topics that help you create efficient programs. Do you remember, we cautioned you to use global variables carefully in JavaScript Variables Tutorial? Well, this article explains the reason why. In this JavaScript garbage collection tutorial, we will cover the different approaches used by various browsers for memory management.

Sit tight, be attentive, and keep in mind: you don’t need to remember it all in one read. Relax and if you get stuck anywhere, try it again.

What is Memory Management?

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. They have their tricks to determine the following three steps of memory management:

  • 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. It may also lead to discrepancies with other applications.

The most important task in managing memory is to detect the unused variables in a program and remove them from memory.
In low-level programming languages like C, we have functions like malloc() for memory allocation and the free keyword to release the memory. We don’t need such approaches while working with a high-level programming language like JavaScript, as memory management is automatic and invisible to the programmer. We have no way to “explicitly” release the memory from the object in JavaScript. First, we’ll talk about the basic notion of memory management while programming: reachability.

Time to brush-up the concept of JavaScript Objects

Reachability of Garbage Collector

JavaScript uses Garbage Collector to decide whether a piece of code requires memory or not. With the help of reachable values, the engine determines when to release the memory. It cannot delete some of the values for obvious reasons:

  • Local values of the running function.
  • Values of other functions used by the current function.
  • Global variables.
  • Some internal values, necessary for the working of JavaScript.

This set of inherently reachable values are roots. Any value that is accessible from a root by a reference or a chain of references is “reachable”. The garbage collector in JavaScript monitors all the objects and various properties, removing those which are unreachable. Let’s explore some examples to understand the concept better.

Case 1: Suppose, there is a “vendor” selling “strawberries” in the market.

var vendor = {
  fruit: "strawberries"
};

Garbage Collector Reachability Example 1

If I want to have access to the strawberries, I need to buy them from the vendor. I doesn’t have direct access to the fruit, but a reference to them through the vendor. What happens if the vendor has no strawberries left?

vendor = null;

Garbage Collector Reachability Example 2 of strawberry & vendor

In this case, the strawberries didn’t magically disappear from this world. But, that particular vendor no longer has any stock left and he displayed a board saying so. This is how we know that we cannot buy strawberries anymore. This means that there are no references to the fruit.

Case 2: But wait, I really do want strawberries since I love them. Also, I’m a resident of this town to know where everything is. What do I do next? I ask the vendor if there is another vendor, who sells strawberries, in town. Nodding yes, he gives me the address of a lady vendor.

var vendor = {
fruit: "strawberries"
};
var ladyVendor = vendor;

Garbage Collector Reachability Example 3 & Case 2

So, what happened here is that I got the reference to another person to gain access to the strawberries. But the next time I want to buy strawberries, I have two references to refer to, the vendor and the ladyVendor. Even if the vendor doesn’t contain the reference to the strawberries anymore, I still have an option to buy them from the ladyVendor. Thus, the fruit now has two references. The image below makes it fairly clear.

Reachability of Garbage Collector Code

Now, if we want to release the memory to the object, I will have to overwrite all the values pointing to it.

I think that you now understand how a garbage collector decides if a value is reachable or not. Let’s see how it responds when it finds non-reachable objects in memory.

Reference Counting Garbage Collection in JavaScript

This is the primitive algorithm used by a garbage collector in browsers. It determines whether the value still has any object referencing it. If the object has zero references pointing to it, that object is said to be “garbage”. The garbage collector detects these objects and releases them from memory.

Circular References

Reference counting Garbage Collection algorithm

This is where the reference counting approach fails. The situation here is that a client is communicating with an employee of my company. This means that the client is referencing with the employee on a technical problem. On the other hand, the employee refers to the client to resolve the issue. The basic relationship is clear from the JavaScript code below.

Code:

<script>
      function DataFlair(employee, client){
        // client and employee creating a cycle
        client.assistant = employee;
        employee.inquirer = client;
        return {
          admin: employee,
          user: client
        }
      }
      // function call with arguments
      var company = DataFlair({
        name: "Mihir" // employee name
      }, {
        name: "Sameer" // client name
      });
    </script>

Screenshot:

Reference Counting Garbage Collection Code
Save the program and go to your browser console to see the output. Just call the variable “company” and start clicking on the arrows at admin and user.

Output:

Reference Counting Garbage Collection Output

Notice that the two objects (employee and client) never stop referencing each other. In this scenario, the objects will never have zero references, thus staying in the memory. Even if the employee “Mihir” leaves the company, the communication between him and “Sameer” is open.

If we want to prevent Mihir from communicating with the client like an assistant, we need to remove the reference of the client to the employee. Since outgoing references hold no value, the garbage collector will release the object’s memory, as shown in the picture below.

Reference counting Garbage Collection algorithm - delete object memory

We can remove these links with the help of the following statements:

delete company.admin;
delete company.user.assistant;

Mark and Sweep Garbage Collection in JavaScript

This is the most popular garbage collection algorithm available to the browsers. The JavaScript engine starts from roots, working its way to the references it can reach from there. The steps followed by this algorithm is as follows:

  • The garbage collector goes through the roots, marking (remembering) them on its way.
  • After it traverses all the roots, it then moves on to the references and marks them as well.
  • The cycle continues until the garbage collector visits all the roots and the references associated with them. It never visits an object twice.
  • After marking all the values reachable from the roots, the garbage collector removes all the objects, except the marked ones.

Mark and sweep Garbage Collection algorithm

Summary

In this JavaScript tutorial, we learned about garbage collection in JS and its working in detail. We learned a little about memory management and why we need to understand the concept. We also discussed the different algorithms used during garbage collection in JavaScript.

Thinking, what to learn next? Don’t worry, check out the JavaScript Errors Tutorial

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *