The JavaScript engine

Garbage collection

Understand reachability, mark-and-sweep collection, generations, and why collection can reclaim only unreachable values.

8 minute lesson

~~~

JavaScript creates objects without asking you to free each one. The engine reclaims memory by finding values that are no longer reachable.

Reachability starts from roots the running program can still access, such as global variables and active call-stack frames. References are then followed from those roots:

let user = {
  name: 'Ada',
  preferences: { theme: 'dark' }
}

user = null

If nothing else references that object graph, it becomes eligible for collection. “Eligible” does not mean “freed immediately.” The engine decides when to collect, and the strategy varies by browser and workload.

Modern collectors divide the work in several ways. For example, they can treat new and long-lived objects differently or perform parts of collection incrementally. These are implementation techniques for reducing disruption, not timing guarantees an application should depend on.

Three consequences matter in application code:

  1. Temporary allocation still costs work even when it is collected soon.
  2. A reachable value cannot be collected, even when the feature no longer needs it.
  3. Memory usage does not have to fall immediately after references are released.

Open DevTools Memory tools, take a heap snapshot, create and discard a large group of objects, and take another snapshot after allowing collection. Focus on which objects remain reachable and their retaining paths. Do not build application logic around forcing garbage collection; production code cannot use it as a reliable cleanup mechanism.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →