DEV Community

Cover image for JavaScript Non-garbage-collection in Objects
Bello Osagie
Bello Osagie

Posted on • Updated on

JavaScript Non-garbage-collection in Objects

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
Enter fullscreen mode Exit fullscreen mode

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' }
Enter fullscreen mode Exit fullscreen mode

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
map.set(bello);

bello = null; // changed/overidden reference

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

weakMap doesn't prevent garbage collection of key objects.

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

Learn more on MDN


Buy me a Coffee


Top comments (0)