The JavaScript garbage collector runs automatically, keeps track of memory locations, and determines which memory locations are free (i.e., safe for reuse). The garbage collector uses the mark and sweep algorithm with some optimizations.
Reachable objects refer to those objects that are accessible and stored in the memory. A root refers to objects that are inherently reachable, these include:
Starting from the root, the garbage collector traverses the objects and marks them as visited. The objects which are unreachable from the roots are unmarked and considered garbage (memory reserved for these objects is later freed).
let fruit = {
name: "Orange",
weight: 130,
};
let orange = fruit;
Fruit contains a reference to the object:
fruit = null;
fruit
no longer contains a reference to the object. However, it is still reachable from orange
and cannot be treated as garbage.
orange = null;
orange
no longer contains a reference to the object. The object is now unreachable and the memory that it occupied will be declared safe for reuse by the garbage collector.
Free Resources