Garbage collection in JS

xmohammedawad

Mohammed Awad

Posted on May 2, 2023

Garbage collection in JS
What happens when something is not needed anymore? How does the JavaScript engine discover it and clean it up?

Reachability

The main concept of memory management in JavaScript is reachability.
There’s a base set of inherently reachable values, that cannot be deleted for obvious reasons.
For instance:

  1. The currently executing function, its local variables and parameters.
  2. Other functions on the current chain of nested calls, their local variables and parameters.
  3. Global variables.

These values are called roots.

Any other value is considered reachable if it’s reachable from a root by a reference or by a chain of references. There’s a background process in the JavaScript engine that is called garbage collector. It monitors all objects and removes those that have become unreachable.

let's dive in and understand how it's work

example

// user has a reference to the object
let user = {
  name: "John"
};
Enter fullscreen mode Exit fullscreen mode

Image describes how Garbage collection work

and If the value of user is overwritten, the reference is lost:

Image describes how Garbage collection clean unreachable elements

Now John becomes unreachable. There’s no way to access it, but if we copied the reference from user to admin and overwritten the value

Then the object is still reachable via admin global variable.

mark-and-sweep

garbage collection algorithm is called “mark-and-sweep”
and these steps are regularly performed:

  1. The garbage collector takes roots and “marks” (remembers) them.
    garbage collector steps

  2. Then it visits and “marks” all references from them.

garbage collector steps

  1. And so on until all reachable references are visited.

garbage collector steps

  1. All objects except marked ones are removed.

garbage collector steps

Summary

  1. Global variables are considered root, so be aware when you declare or reference them.
  2. Outgoing references do not matter. Only incoming ones can make an object reachable.

all my images and content from javascript.info. you can learn more and explore more complex examples on
JavaScript info

💖 💪 🙅 🚩
xmohammedawad
Mohammed Awad

Posted on May 2, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related