2

I am trying to understand FinalizationRegistry in JavaScript. As per the MDN docs the FinalizationRegistry callback function will be called as soon as the object it is weakly referencing is lost. I tried with a simple example but doesn't seem to work.

const obj = {a:'GC'}
registry = new FinalizationRegistry(value => {
  console.log(value);
});
registry.register(obj, "Garbage collected");
delete obj; //deletes obj from the global context, but FinalizationRegistry registry callback not called

Can someone please give a simple working example?

Boris
  • 103
  • 1
  • 9
  • 2
    There's a section in the "notes" part of the MDN docs. --- _"A conforming JavaScript implementation, even one that does garbage collection, **is not required to call cleanup callbacks**. When and whether it does so is entirely down to the implementation of the JavaScript engine. When a registered object is reclaimed, any cleanup callbacks for it may be called then, or some time later, **or not at all**."_ – evolutionxbox Dec 04 '21 at 23:37
  • @evolutionxbox thanks, I read that, I am trying to understand if there is any way we can implement FinalizationRegistry callback in any use-case with absolute certainty? – Boris Dec 04 '21 at 23:43
  • 1
    You cannot `delete` a `const`. – Bergi Dec 05 '21 at 05:28
  • @Boris I'm not sure you can, no – evolutionxbox Dec 05 '21 at 16:19

0 Answers0