DEV Community

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

Posted on • Edited on

1

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


Sentry blog image

Identify what makes your TTFB high so you can fix it

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay