JavaScript Non-garbage-collection in Objects

JavaScript Non-garbage-collection in Objects

Mar 9, 2021·

2 min read

Play this article

Visual Composer Website Builder

Garbage collection is a term used in computer programming to describe the process of finding and deleting objects which are no longer being referenced by other objects. In other words, garbage collection is the process of removing any objects which are not being used by any other objects — MDN

JavaScript engines store values in memory for reachability and these values reference can be changed or removed.

See the example below:

let bello = { name: "Bello" }; //accessible

bello= null; // reference changed or object removed

An object in an array implies that the object will remain alive provided the array is alive even if there are no other references to it.

let bello = { name: "Bello" };

const array = [ bello ]; // if array exist, object will exist

bello = null; // changed/overidden reference

console.log( array[0] ); // { name: 'Bello' }

The above is not a garbage-collection because the object still exists in the array.

Same as the example above, an object as a key in a Map exists in the memory provided the Map is alive.

See another example:

let bello = { name: "Bello" };

const map = new Map(); // if map exist, object will exist

bello = null; // changed/overidden reference

console.log( map.keys() ); // [Map Iterator] { { name: 'Bello' } }
// Map prevents garbage-collection

weakMap doesn't prevent garbage collection of key objects.

We will see the use of weakMap in the next article.