Skip to content

How does garbage collection work?

Updated Nov 30, 20263 min readBased on official documentation
How does garbage collection work?

In short

Garbage collection is an automatic process that finds memory a program no longer needs and frees it. Instead of the developer releasing memory by hand, the language runtime watches which objects are still reachable and reclaims the rest. JavaScript engines use this approach, most commonly a mark-and-sweep algorithm.

Why memory needs cleaning up

Every program stores data in memory. When you create a number, a string, an object or a function, the runtime sets aside some memory for it. That memory is limited, so it has to be given back once the data is no longer used.

Most memory use follows the same life cycle. The program allocates memory, reads and writes it, and then releases it when it is no longer needed. In low-level languages such as C, the developer handles the release step by hand. In high-level languages such as JavaScript, the runtime handles most of it for you. This is where garbage collection comes in.

The hard part is deciding when memory is no longer needed. A garbage collector can only approximate this. Checking for certain whether a piece of memory will ever be used again is a problem no program can solve in general, so collectors use a practical rule instead.

How references decide what is alive

The main idea behind garbage collection is the reference. An object references another object if it can reach it, either directly through a property or indirectly through something like a prototype. A function scope or the global scope can also hold references.

One early approach is reference counting. Each object keeps a count of how many references point to it. When the count drops to zero, the object is treated as garbage and its memory is reclaimed. This is simple, but it fails on circular references. If two objects point at each other and nothing else points at them, their counts never reach zero, even though the program can no longer reach them. Because of this weakness, modern JavaScript engines no longer use reference counting.

How mark-and-sweep works

Modern engines use mark-and-sweep. The garbage collector starts from a set of known roots. In JavaScript, the global object is the root. It then follows every reference from the roots, marking each object it reaches as alive. When it is done, any object that was not marked is unreachable, and the collector sweeps those objects away and reclaims their memory.

This approach handles cycles well. Two objects that reference each other but cannot be reached from the roots are simply swept. Engines have added many refinements over the years, such as generational, incremental and concurrent collection, but these improve how the algorithm runs rather than changing the rule that unreachable objects are garbage.

What you cannot control

Because the collector decides when to run, you cannot force a collection from ordinary JavaScript code. To free an object, you make sure nothing reachable still points to it, for example by setting a variable to null or removing an entry from a collection. Memory is then reclaimed at a time the engine chooses.

For debugging, some runtimes offer flags. Node.js, for example, lets you raise the heap size limit with a flag, and it can expose the garbage collector for testing. These options depend on the runtime and are generally not available in browsers.

Data structures that help

JavaScript provides WeakMap and WeakSet to work with the collector. They look like Map and Set, but they hold their keys weakly. If nothing else in the program references a key object, the collector can reclaim that entry. This is useful for caching data tied to an object, because the cache does not keep the object alive. WeakMap and WeakSet only accept objects and symbols as keys, since primitive values such as numbers and strings cannot be tracked this way.

Common mistakes

The most common cause of memory leaks is an object that stays reachable without being needed. A forgotten event listener, a global variable that keeps growing, or a cache with no limit can all hold memory indefinitely. Check what your code keeps references to, and remove those references when the data is no longer useful.

FAQ

Does JavaScript let me run garbage collection manually?

No. The language does not expose a garbage collector API, and it is not expected to in the core language. Engines may offer opt-in flags for debugging, but ordinary code cannot trigger a collection.

Why do circular references not cause leaks in modern engines?

Modern engines use mark-and-sweep, which starts from roots and marks only reachable objects. Two objects that point at each other but cannot be reached from the global object are unreachable, so they are collected.

What is the difference between Map and WeakMap?

A Map holds its keys strongly, so keys stay in memory as long as the map exists. A WeakMap holds keys weakly, so an entry can be collected once nothing else references its key object.

How do I free memory for an object?

Make sure no reachable reference points to it. Setting a variable to null or removing the object from a collection is usually enough. The engine then reclaims the memory at a time of its choosing.

Sources

This page is based on the official documentation below. Read it for full detail.

Garbage collection — official documentation ↗

Garbage collection in the news

blozhikDeveloper news from across the web, explained. Every story links to its original sources.