Heard of weak refs in JavaScript?

Nishu Goel
2 min readJun 5, 2021

use case: have a reference to an object without forcing it to stay in memory. don’t need it now? let the garbage collector wipe it now.
might need it later? you can always recreate the object from the reference to use it now.

Let’s assume we have a giant object in javascript with a reference to it. This object stays in the memory until there is some reference to it. In special scenarios, being very fastidious about the performance of your application, you might want to ensure that an object taking tons of memory space being this giant object, doesn’t need to be present in the memory the whole time you have a reference to it. You should be able to just recreate the object using the reference that you made and while it is not being used, the garbage collection mechanism of JavaScript will take care of it.

This proposal was made July 2020 for JavaScript. See here:

This use case is very specific to advanced optimising techniques.

Finalisers

This is one thing about the garbage collection process where we always want to see what is happening under the hood. But how do we know?

Finalisers help us with that. So, we could log some information that we’d like to see and when GC (garbage collector) comes into action and remove something from the memory, we get the logged info, therefore helping us debug the app or just understand better what is going on.

We can read the meeting notes for this here.

Interested to dive deeper? See all finished proposals here: https://github.com/tc39/proposals/blob/master/finished-proposals.md

--

--

Nishu Goel

Engineering stuff @epilotGmbH; Web Google Developer Expert; Microsoft MVP;