How does the Garbage Collector work in JavaScript?
NicolasBrondinBernard
# What is a garbage collector and how does JavaScript manage its memory release? A **garbage collector** (GC) is a mechanism responsible for automatically managing a program's memory. Its role is to reclaim memory that is no longer being used by the application, in order to free it up and prevent memory leaks. This process is essential in languages like JavaScript, where developers do not manually manage memory allocation and deallocation, unlike in languages such as C or C++. ## How does memory allocation work in JavaScript? In JavaScript, memory is allocated automatically when you create variables, objects, functions, etc. For example: ```js let obj = { name: "John" }; // memory allocation for this object let arr = [1, 2, 3]; // memory allocation for this array ``` Each time an object, array, or other data structure is created, the JavaScript engine (such as V8 for Chrome and Node.js) reserves memory to store this data. ## How does JavaScript's garbage collector work? JavaScript's garbage collector relies mainly on an algorithm called **mark-and-sweep**. Here is how it works: 1. **Marking**: The garbage collector goes through all objects in memory and marks those that are still accessible, i.e., referenced by the code currently in use (via variables, functions, closures, etc.). 2. **Sweeping**: Once the marking is done, the garbage collector removes objects that were not marked, meaning those no longer referenced by any part of the code, and frees the memory associated with them. Here is a simple example to illustrate this concept: ```js function createObject() { let obj = { name: "Alice" }; return obj; } let myObj = createObject(); // myObj references the object created in createObject myObj = null; // the object is no longer referenced, it becomes eligible for garbage collection ``` In this example, once `myObj` is set to `null`, the object `{ name: "Alice" }` is no longer accessible from anywhere in the code. The garbage collector will then detect it as unreachable and will free the memory it occupied. ## The concept of "reachability" The core principle behind the garbage collector is **reachability**. An object is considered "reachable" if it can be accessed directly or indirectly by the running code. As long as an object is reachable, it will not be collected. Here are a few examples of what makes an object reachable: - A variable in the current scope. - A function's closure. - An object referenced by another object still in use. As soon as an object becomes unreachable (for example, when no variable points to it anymore), it becomes eligible for garbage collection. ## Limitations and best practices Even though JavaScript's garbage collector automates memory management, some practices can help avoid memory leaks: - **Avoid unnecessary global references**: Objects stored in global variables remain accessible throughout the application's execution, which can prevent them from being collected. - **Properly manage event listeners**: If you add event listeners without removing them when they are no longer needed, this can create references that prevent memory from being freed. - **Watch out for closures**: Poorly managed closures can retain references to objects longer than necessary, which can lead to memory leaks. ## Conclusion JavaScript's garbage collector is a powerful tool that frees developers from manually managing memory, while ensuring efficient resource usage. By understanding how it works, particularly through the mark-and-sweep algorithm and the concept of reachability, you can write more optimized code and avoid common pitfalls related to memory management, such as memory leaks.

Article published on 15/03/2021, last updated on 10/08/2026
The Garbage Collector, also called GC, or sometimes "ramasse-miettes" in French, refers to an automated process whose purpose is to free up dynamic memory (heap) that is unused by a program as it executes.
If the concepts of primitives, references, and dynamic memory (heap) are not familiar to you, I recommend reading my article dedicated to them!
In low-level languages like C for example, it is possible to manage dynamic memory manually, in three distinct phases:
- Allocation of a memory space (malloc(...), calloc(...))
- Usage (initialization/writing then reading)
- Freeing memory that is no longer needed (free(...))
But in Javascript, when you create a reference to a new object, all memory allocation is done automatically, you don't need to know how many bytes you need to reserve.
And you also don't need to free the dynamic memory used, because it's the Javascript engine that handles this, thanks to its "Garbage Collector".
Note that I'm talking about dynamic memory, because primitive objects stored in static memory are erased as soon as you exit the scope in which they were created.
How it works
The problem
Before looking at the solution, we need to fully understand the problem. Let's take a memory zone that we'll call M1, which takes up 200KB of space in dynamic memory and to which 3 references from different parts of our program are pointing.
For our program not to be too memory-hungry, we need to be able to free up the huge space taken as soon as this memory zone is no longer used.
The problem is that the JS engine alone cannot predict in advance at what point during the execution of our program this memory zone will no longer be pointed to by any reference.
This is why we need a Garbage Collector, whose job will be to discover unreferenced memory cells in order to free them.
A simple approach, reference-counting
There are garbage collectors in many languages, and each implements a different detection algorithm, some more or less efficient than others. One of the first approaches used was "reference-counting".
This algorithm simply consists of storing, for each zone of dynamic memory used, the number of references pointing to that zone, then incrementing this number with each new reference and decrementing it each time a reference is removed.
When the number of references drops to 0, then it's time to free that memory zone.
This approach works but poses a few problems, two of the main ones being:
- The garbage collector is almost constantly active, sometimes just to free a single small memory zone, thus losing efficiency
- The algorithm is unable to free memory zones pointed to by circular references
A circular reference can be created when an object references itself, or when two objects each contain a reference to the other.
In the case of a circular reference, the number of references can never drop to zero and the memory zone will never be freed, this is what's known as a memory leak (there are many other types).
To address this, Javascript instead implements another algorithm called "Mark and Sweep".
The Mark and Sweep approach
Javascript, regardless of its execution environment (Web Browser or NodeJS), provides a root object to which all top-level variables and functions are attached.
These objects are "window" in the browser and "process" in NodeJS
This means that any object in a Javascript application must remain accessible by going back up from the root object, all the way to the object by traversing all the necessary references.
If we look at it the other way around, this means that any memory zone allocated by Javascript but unreachable from the root object is actually a zone that can be freed!
The garbage collector's Mark and Sweep algorithm therefore consists of "flagging" all objects that are unreachable from the root so that they can all be collected at once as soon as Javascript needs to free up memory.
This approach thus solves the two problems presented in the "reference-counting" approach, because a circular reference is cut off from the root object as soon as no other reference points to it.
Note that the garbage collector's activity is therefore unpredictable, and that its execution can introduce other side effects such as slowing down the application at that moment.
No spam. Only free content, news, and ever more resources to level up your skills!
Join +1500 developers
No comments yet