MediumModern JS📖 Theory Question

What are WeakRef and FinalizationRegistry?

💡

Hint

WeakRef: hold object without preventing GC; FinalizationRegistry: callback when object is collected

Full Answer

Advanced memory management APIs — use sparingly and only for performance optimizations.

// WeakRef — holds a weak reference (doesn't prevent GC)
let bigObject = { data: new Array(1_000_000).fill('*') };
const ref = new WeakRef(bigObject);

bigObject = null; // release strong reference → GC can now collect it

// Access via .deref() — returns undefined if already collected
const obj = ref.deref();
if (obj) {
  console.log('Still alive:', obj.data.length);
} else {
  console.log('Was garbage collected');
}

// FinalizationRegistry — callback when a registered object is collected
const registry = new FinalizationRegistry((heldValue) => {
  console.log('Collected! Clean up:', heldValue);
  cleanupResources(heldValue);
});

let target = { name: 'Alice' };
registry.register(target, 'alice-cleanup-token');
// target can now be GC'd — callback fires sometime after

Important: GC timing is non-deterministic. Don't use these for program correctness — only for optional caching or cleanup of non-critical resources.

💡 WeakRef + FinalizationRegistry are for library authors building caches that should automatically clean up. App code rarely needs these — use WeakMap instead.

More Modern JS Questions

MediumWhat are generators and when would you use them?→EasyWhat is optional chaining (?.) and nullish coalescing (??)?→EasyWhat are tagged template literals and what are they used for?→EasyExplain destructuring for objects and arrays — including defaults, renaming, rest, and nesting.→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint